﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using EMANIFEST.Common;
using EMANIFEST.Common.Validation;
using EMANIFEST.Dtos;
using EMANIFEST.eManifestService;

using EMANIFEST.CONTROLTEMPLATES.Emanifest_UI;

namespace EMANIFEST.PROFILE.recordabsolute2
{
    public partial class recordabsolute2UserControl : UserControl
    {

        #region Variables
        string gvUniqueID = String.Empty;
        int gvNewPageIndex = 0;
        int gvEditIndex = -1;
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            //SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
            //ribbon.Visible = false;
            if (!IsPostBack)
            {
                string rid = Request.QueryString["rid"];

                if (!string.IsNullOrEmpty(rid))
                {

                    hfDocumentID.Value = rid;

                    #region Loading data
                    #region Image
                    #endregion

                    #region Load data & Set permission
                    string cachName = string.Format(EmanifestCommon.CachePermissionFormat, EmanifestUser.FBAUserId, rid);
                    UserInfomation userInfo = Cache[cachName] as UserInfomation;
                    EmanifestServiceClient client = new EmanifestServiceClient();
                    if (userInfo == null)
                    {
                        userInfo = client.GetUserInfoByDocumentId(new Guid(rid), EmanifestUser.FBAUserId);
                    }

                    var docId = new Guid(rid);
                    DocumentDto documentDto = client.GetDocumentDetail(docId, EmanifestUser.FBAUserId);

                    Dictionary<Guid, PortDto> dicPorts = client.GetDicPortInUsed();
                    client.Close();
                    #endregion

                    #region Binding
                    BindingDocumentBasic(documentDto);

                    if (userInfo == null || userInfo.AccessForm == 0)
                    {
                        tabDocument.Enabled = false;
                    }
                    else
                    {
                        bool isTabActive = false;
                        if ((userInfo.AccessForm & EmanifestCommon.AccessGoodFormBitwise) != EmanifestCommon.AccessGoodFormBitwise)
                        {
                            tabDocument.Tabs[0].Enabled = tabDocument.Tabs[8].Enabled = false;
                        }
                        else
                        {
                            Session["DocumenType"] = ((int)EnumDoucmentType.Good).ToString();
                            grdGoodDecralationItem.DataSourceID = "odsHangHoa";
                            grdGoodDecralationItem.DataBind(); //DataSourceID="odsHangHoa"
                            isTabActive = true;
                            tabDocument.ActiveTabIndex = 0;

                            client = new EmanifestServiceClient();

                            GoodDeclarationDto goodDec = client.GetGoodDeclarationByDocumentId(new Guid(hfDocumentID.Value), EmanifestUser.FBAUserId);
                            if (goodDec != null)
                            {
                                txtGoodDecNumberOfPackage0.Text = lblGoodDecNumberOfPackage.Text = goodDec.NumberOfPackage.ToString();
                                txtKindOfPackages0.Text = lblKindOfPackages.Text = goodDec.KindOfPackages;
                                txtGoodDecralationId.Text = goodDec.GoodDeclarationId.ToString();
                            }
                            client.Close();
                            lblGoodDecralationStatus.Text = string.Empty;
                        }

                        if ((userInfo.AccessForm & EmanifestCommon.AccessHouseBillFormBitwise) != EmanifestCommon.AccessHouseBillFormBitwise)
                            tabDocument.Tabs[1].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 1;
                                btnHouseBillTrigger_Click(null, null);
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessGeneralFormBitwise) != EmanifestCommon.AccessGeneralFormBitwise)
                        {
                            tabDocument.Tabs[2].Enabled = false;
                        }
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 2;
                                BindingDocumentDetail(documentDto);
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessCrewFormBitwise) != EmanifestCommon.AccessCrewFormBitwise)
                            tabDocument.Tabs[3].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 3;
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessCrewEffectFormBitwise) != EmanifestCommon.AccessCrewEffectFormBitwise)
                            tabDocument.Tabs[4].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 4;
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessShipStoreFormBitwise) != EmanifestCommon.AccessShipStoreFormBitwise)
                            tabDocument.Tabs[5].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 5;
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessPassengerFormBitwise) != EmanifestCommon.AccessPassengerFormBitwise)
                            tabDocument.Tabs[6].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 6;
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessDangerousFormBitwise) != EmanifestCommon.AccessDangerousFormBitwise)
                            tabDocument.Tabs[7].Enabled = false;
                        else
                        {
                            if (!isTabActive)
                            {
                                isTabActive = true;
                                tabDocument.ActiveTabIndex = 7;
                            }
                        }
                        if ((userInfo.AccessForm & EmanifestCommon.AccessGeneralFormBitwise) == EmanifestCommon.AccessGeneralFormBitwise)
                        {
                            BindingDocumentDetail(documentDto);
                        }
                        //if ((userInfo.AccessForm & EmanifestCommon.AccessOtherFormBitwise) != EmanifestCommon.AccessOtherFormBitwise)
                        //{
                        //    tabDocument.Tabs[1].Enabled = tabDocument.Tabs[2].Enabled = tabDocument.Tabs[3].Enabled = tabDocument.Tabs[4].Enabled =
                        //        tabDocument.Tabs[5].Enabled = tabDocument.Tabs[6].Enabled = tabDocument.Tabs[7].Enabled = tabDocument.Tabs[9].Enabled = tabDocument.Tabs[10].Enabled = false;
                        //}
                        //else
                        //{
                        //    BindingDocumentDetail(documentDto, dicPorts);
                        //}
                        tabDocument.Tabs[9].Enabled = tabDocument.Tabs[10].Enabled = false;
                    }
                    #endregion
                    #endregion
                }
                //txtHoRO.Attributes.Add("readonly", "readonly");
                //txtTenRO.Attributes.Add("readonly", "readonly");
                txtSoHoChieuRO.Attributes.Add("readonly", "readonly");
                txtNoiSinhRO.Attributes.Add("readonly", "readonly");
                txtChucDanhRO.Attributes.Add("readonly", "readonly");
            }
            //cNgayHetHan.ID = DateTime.Now.ToString() + "1";
            //cNgaySinh.ID = DateTime.Now.ToString() + "2";

            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileGoodDecralation).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileHouseBill).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileCrew).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileCrewEffect).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileShipStore).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFilePassenger).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileGeneralDecralation).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);
            ((EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile)upFileDangerousGood).UploadCompleted += new EMANIFEST.CONTROLTEMPLATES.Emanifest_UI.UploadFile.UploadFileCompleted(UploadFile_Completed);

        }


        protected void btnShowReport_OnClick(object sender, EventArgs e)
        {

        }

        protected void odsHangHoa_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            //            If e.ExecutingSelectCount = TrueThen
            //e.InputParameters.Add(“paramname”, value)
            //End If
            ods_Selecting(sender, e);
        }


        #region ODS Selecting
        protected void odsCrews_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsHouseBill_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsCrewEffect_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsShipStore_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsPassenger_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsDangerousGood_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        protected void odsMasterBill_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            ods_Selecting(sender, e);
        }
        private void ods_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (e.InputParameters["docId"] != null)
                e.InputParameters["docId"] = hfDocumentID.Value;
            else
                e.InputParameters.Add("docId", hfDocumentID.Value);

            if (e.InputParameters["userId"] != null)
                e.InputParameters["userId"] = EmanifestUser.FBAUserId;
            else
                e.InputParameters.Add("userId", EmanifestUser.FBAUserId);
        }

        #region ODS Item Selecting using ParentId
        protected void odsHouseBillItem_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (e.InputParameters["userId"] != null)
                e.InputParameters["userId"] = EmanifestUser.FBAUserId;
            else
                e.InputParameters.Add("userId", EmanifestUser.FBAUserId);
        }

        protected void odsDangerousGoodItem_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (e.InputParameters["userId"] != null)
                e.InputParameters["userId"] = EmanifestUser.FBAUserId;
            else
                e.InputParameters.Add("userId", EmanifestUser.FBAUserId);
        }
        #endregion
        #endregion

        #region ODS Children Item selected
        private bool LoadDangerousGoodItemDataEmpty
        {

            //  some controls that are used within a GridView,

            //  such as the calendar control, can cuase post backs.

            //  we need to preserve LoadDataEmpty across post backs.

            get { return (bool)(ViewState["LoadDangerousGoodItemDataEmpty"] ?? false); }

            set { ViewState["LoadDangerousGoodItemDataEmpty"] = value; }

        }
        protected void odsDangerousGoodItem_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            if (e.ReturnValue == null)
            {
                List<DangerousGoodItemDto> lst = e.ReturnValue as List<DangerousGoodItemDto>;
                if (lst == null)
                {
                    lst = new List<DangerousGoodItemDto>();
                }
                if (lst.Count == 0)
                {
                    DangerousGoodItemDto item = new DangerousGoodItemDto()
                    {
                        DangerousGoodId = new Guid(txtDangerousGoodId.Text),
                        FlashPoint = 0,
                        GoodClass = string.Empty,
                        GrossWeight = 0,
                        MarinePollutant = string.Empty,
                        NumberContainer = string.Empty,
                        NumberOfPackage = string.Empty,
                        PackingGroup = string.Empty,
                        ProperShipping = string.Empty,
                        RefNumber = string.Empty,
                        StowagePosition = string.Empty,
                        SubsidiaryRisk = string.Empty,
                        UNNumber = string.Empty
                    };
                    lst.Add(item);
                    LoadDangerousGoodItemDataEmpty = true;
                }
                else
                    LoadDangerousGoodItemDataEmpty = false;

            }
        }


        #endregion
        #region Trigger click

        protected void btnGoodDecralationTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.Good).ToString();
            //lblGoodDecralationStatus.Text = Session["DocumenType"].ToString();
            lblGoodDecralationStatus.Text = string.Empty;
        }
        protected void btnMasterBillTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.Good).ToString();
            //grdMasterBill.DataSourceID = "odsMasterBill";
            try
            {

                grdMasterBill.DataSourceID = "odsMasterBill";
                grdMasterBill.DataBind();
                this.lblMasterBillTabLoadStatus.Text = string.Empty;
                //loaderPlaceholder.InnerHtml = "";
            }
            catch (Exception ex)
            {
                this.lblMasterBillTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnHouseBillTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.HouseBill).ToString();
            try
            {
                //BindingHouseBillTab();
                grdHouseBill.DataSourceID = "odsHouseBill";
                //grdHouseBill.DataSource = lstHouse;
                grdHouseBill.DataBind();
                this.lblHouseBillLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblHouseBillLoadStatus.Text = ex.Message;
            }
            finally
            {

            }
        }
        protected void btnGeneralDeclarationTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.General).ToString();
            EmanifestServiceClient client = null;
            try
            {
                client = new EmanifestServiceClient();
                GeneralDeclarationDto general = client.GetGeneralDeclarationByDocumentId(new Guid(hfDocumentID.Value), EmanifestUser.FBAUserId);
                BindGeneralDecralationItem(general);

                this.lblGeneralDecralationTabLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblGeneralDecralationTabLoadStatus.Text = ex.Message;
            }
            finally
            {
                if (client != null) client.Close();
            }
        }
        protected void btnCrewsTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.Crews).ToString();
            try
            {
                grdCrews.DataSourceID = "odsCrews";
                grdCrews.DataBind();
                this.lblCrewTabLoadStatus.Text = string.Empty;// Session["DocumenType"].ToString();
            }
            catch (Exception ex)
            {
                this.lblCrewTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnCrewEffectTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.CrewEffect).ToString();
            try
            {
                grdCrewEffect.DataSourceID = "odsCrewEffect";
                grdCrewEffect.DataBind();
                this.lblCrewEffectTabLoadStatus.Text = string.Empty;// Session["DocumenType"].ToString();
            }
            catch (Exception ex)
            {
                this.lblCrewEffectTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnShipStoreTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.Stores).ToString();
            try
            {
                BindShipStore();
                grdShipStore.DataSourceID = "odsShipStore";
                grdShipStore.DataBind();
                this.lblShipStoreTabLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblShipStoreTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnPassengerTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.Passenger).ToString();
            try
            {
                grdPassenger.DataSourceID = "odsPassenger";
                grdPassenger.DataBind();
                this.lblPassengerTabLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblPassengerTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnDangerousGoodTrigger_Click(object sender, EventArgs args)
        {
            Session["DocumenType"] = ((int)EnumDoucmentType.GoodDangerous).ToString();
            //EmanifestServiceClient client = null;
            try
            {
                Guid docId = new Guid(hfDocumentID.Value);
                //client = new EmanifestServiceClient();
                //DangerousGoodDto good = client.GetDangerousByDocumentId(docId, EmanifestUser.FBAUserId);
                //Dictionary<Guid, PortDto> dicPort = client.GetDicPortInUsed();
                //client.Close();

                //if (good != null && good.DocumentId == docId)
                {
                    //txtContNumber.Text = good.ContNumber;
                    //txtContSealNumber.Text = good.ContSealNumber;
                    //PortDto port;
                    //if (!string.IsNullOrEmpty(good.PortNameOfLoad))
                    //    if (dicPort.TryGetValue(good.PortOfLoad, out port))
                    //        txtPortOfLoad.Text = port.Name;
                    //    else
                    //        txtPortOfLoad.Text = good.PortNameOfLoad;
                    //if (dicPort.TryGetValue(good.PortOfUnload, out port))
                    //    txtPortOfUnLoad.Text = port.Name;

                    grdDangerousGood.DataSourceID = "odsDangerousGood";
                    grdDangerousGood.DataBind();
                    this.lblDangerousGoodLoadStatus.Text = string.Empty;
                }
                //else
                //    this.lblDangerousGoodLoadStatus.Text = "Không có bản khai nào";
            }
            catch (Exception ex)
            {
                this.lblDangerousGoodLoadStatus.Text = ex.Message;
            }
        }
        protected void btnImgMasterBillTrigger_Click(object sender, EventArgs args)
        {
            try
            {
                imgMasterBill.ImageUrl = string.Format("{0}?rid={1}&uid={2}&type=master", imgMasterBill.ImageUrl, hfDocumentID.Value, EmanifestUser.FBAUserId);
                this.lblImgMasterBillTabLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblImgMasterBillTabLoadStatus.Text = ex.Message;
            }
        }
        protected void btnImgHouseBillTrigger_Click(object sender, EventArgs args)
        {
            try
            {
                imgHouseBill.ImageUrl = string.Format("{0}?rid={1}&uid={2}&type=house", imgHouseBill.ImageUrl, hfDocumentID.Value, EmanifestUser.FBAUserId);
                this.lblImgHouseBillTabLoadStatus.Text = string.Empty;
            }
            catch (Exception ex)
            {
                this.lblImgHouseBillTabLoadStatus.Text = ex.Message;
            }
        }


        #endregion

        #region Binding
        private void BindingDocumentBasic(DocumentDto documentDto)
        {
            if (documentDto != null)
            {
                //Binding thong tin ho so
                lblShip.Text = documentDto.Ship.ShipName;
                lblPort.Text = documentDto.Port.Name;
                lblMasterName.Text = documentDto.MasterName;
                lblDocument.Text = documentDto.Name;
                lblArriveTime.Text = documentDto.ArrivalDate.ToString(Constant.FormatDate);
            }

        }

        private void BindingHouseBillTab()
        {
            grdHouseBill.DataSourceID = "odsHouseBill";
            //grdHouseBill.DataSource = lstHouse;
            grdHouseBill.DataBind();

            this.lblHouseBillLoadStatus.Text = string.Empty;
        }
        private void BindingDocumentDetail(DocumentDto documentDto)
        {
            if (documentDto != null)
            {
                #region Binding data
                //Binding thong tin chung.

                if (documentDto.GeneralDeclarations != null && documentDto.GeneralDeclarations.Count > 0)
                {
                    GeneralDeclarationDto general = documentDto.GeneralDeclarations[0];
                    BindGeneralDecralationItem(general);

                    lnkAddGeneralDecralation.Visible = false;
                    lnkEditGeneralDecralation.Visible = true;
                }
                else
                {
                    BindGeneralDecralationItem(null);
                    txtGeneralDeclarationId.Text = string.Empty;

                    lnkAddGeneralDecralation.Visible = true;
                    lnkEditGeneralDecralation.Visible = false;
                }


                #endregion
            }


        }
        #endregion

        #region GoodDecralation Tab
        #region Add/Edit Crew Effect

        protected void grdGoodDecralationItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //List<CrewDto> items = new List<CrewDto>();

            //if (ViewState["crewsitems"] != null)
            //{
            //    items = (List<CrewDto>)ViewState["crewsitems"];
            //}
            int index = 0;
            string strGoodDecralationId = string.Empty;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetGoodDecralation();
                index = int.Parse(e.CommandArgument.ToString());
                strGoodDecralationId = this.grdGoodDecralationItem.DataKeys[index].Value.ToString();
                txtGoodDecralationItemId.Text = strGoodDecralationId;

                BindGoodDecralationItem(index);

                this.popupGoodDecralation.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strGoodDecralationId = this.grdGoodDecralationItem.DataKeys[index].Value.ToString();
                Guid GoodDecralationId = new Guid(strGoodDecralationId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteCrewById(GoodDecralationId);
                client.Close();
                grdGoodDecralationItem.DataBind();
            }

        }
        protected void lnkAddGoodDecralationItem_Click(object sender, EventArgs e)
        {
            ResetGoodDecralation();
            this.popupGoodDecralation.Show();
        }

        #region Reset/Bind
        private void ResetGoodDecralation()
        {
            txtGoodDecralationItemId.Text = string.Empty;

            txtGoodDecMasterBillNo.Text = string.Empty;
            txtGoodDecConsigner.Text = string.Empty;
            txtGoodDecConsignee.Text = string.Empty;
            txtGoodDecNotificatedParty.Text = string.Empty;
            txtGoodDecContNumber.Text = string.Empty;
            txtGoodDecContSealNumber.Text = string.Empty;
            txtGoodDecGoodDescription.Text = string.Empty;
            txtGoodDecNetWeight.Text = string.Empty;
            txtGoodDecGrossWeight.Text = string.Empty;
            txtGoodDecDemension.Text = string.Empty;
        }
        private void BindGoodDecralationItem(int index)
        {
            if (index < 0)
                return;
            GridViewRow row = grdGoodDecralationItem.Rows[index];
            txtGoodDecralationItemId.Text = this.grdGoodDecralationItem.DataKeys[index].Value.ToString();

            int i = 0;
            txtGoodDecMasterBillNo.Text = (row.Cells[i++].Text);
            txtGoodDecConsigner.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtGoodDecConsignee.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtGoodDecNotificatedParty.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtGoodDecContNumber.Text = (row.Cells[i++].Text);
            txtGoodDecContSealNumber.Text = (row.Cells[i++].Text);
            txtGoodDecGoodDescription.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtGoodDecNetWeight.Text = (row.Cells[i++].Text);
            txtGoodDecGrossWeight.Text = (row.Cells[i++].Text);
            txtGoodDecDemension.Text = (row.Cells[i++].Text);
        }
        #endregion
        #endregion
        #region Save/Update

        protected void btnUpdateGoodDecralation_Click(object sender, EventArgs e)
        {
            Guid goodId;
            if (string.IsNullOrEmpty(txtGoodDecralationId.Text))
                goodId = Guid.NewGuid();
            else
                goodId = new Guid(txtGoodDecralationId.Text);
            GoodDeclarationDto item = new GoodDeclarationDto()
            {
                GoodDeclarationId = goodId,
                CreatedDate = DateTime.Now,
                CreaterId = EmanifestUser.FBAUserId,
                DocumentId = new Guid(hfDocumentID.Value),
                Decription = string.Empty,
                KindOfPackages = txtKindOfPackages0.Text,
                NumberOfPackage = int.Parse(txtGoodDecNumberOfPackage0.Text)
            };
            EmanifestServiceClient client = new EmanifestServiceClient();
            ResponseDto resp = client.SaveGoodDeclarationRecord(item);
            client.Close();
            if (resp.IsSuccess)
            {
                lblGoodDecNumberOfPackage.Text = txtGoodDecNumberOfPackage0.Text;
                lblKindOfPackages.Text = txtKindOfPackages0.Text;
            }
            else
                EmanifestCommon.ShowMessage(this.Page, "Cập nhật hồ sơ không thành công.");
            //item.NumberOfPackage = txtN
        }
        protected void btnUpdateGoodDecralationItem_Click(object sender, EventArgs e)
        {
        }
        #endregion

        #region validation
        private string ValidationFormGoodDecralationItem()
        {
            StringBuilder error = new StringBuilder();

            if (!txtGoodDecMasterBillNo.Text.HadValue())
            {
                error.Append("Số vận đơn là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecMasterBillNo.Text.IsLessOrEqualLength(20))
                {
                    error.Append("Số vận đơn tối đa 20 kí tự.").Append("</br>");
                }

            if (!txtGoodDecContNumber.Text.HadValue())
            {
                error.Append("Số hiệu container là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecContNumber.Text.IsLessOrEqualLength(35))
                {
                    error.Append("Số hiệu container tối đa 35 kí tự.").Append("</br>");
                }

            if (!txtGoodDecContSealNumber.Text.HadValue())
            {
                error.Append("Số niêm phong container là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecContSealNumber.Text.IsLessOrEqualLength(35))
                {
                    error.Append("Số niêm phong container tối đa 35 kí tự.").Append("</br>");
                }

            if (!txtGoodDecNetWeight.Text.HadValue())
            {
                error.Append("Trọng lượng tịnh là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecNetWeight.Text.IsNumber())
                {
                    error.Append("Trọng lượng tịnh phải là số").Append("</br>");
                }

            if (!txtGoodDecGrossWeight.Text.HadValue())
            {
                error.Append("Tổng trọng lượng là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecGrossWeight.Text.IsNumber())
                {
                    error.Append("Tổng trọng lượng phải là số").Append("</br>");
                }

            if (!txtGoodDecDemension.Text.HadValue())
            {
                error.Append("Kích thước/Thể tích là bắt buộc").Append("</br>");
            }
            else
                if (!txtGoodDecDemension.Text.IsNumber())
                {
                    error.Append("Kích thước/Thể tích phải là số").Append("</br>");
                }

            if (!txtGoodDecGoodDescription.Text.HadValue())
            {
                error.Append("Tên hàng/mô tả hàng hóa là bắt buộc").Append("</br>");
            }
            if (!txtGoodDecConsigner.Text.HadValue())
            {
                error.Append("Người gửi hàn là bắt buộc").Append("</br>");
            }
            if (!txtGoodDecConsignee.Text.HadValue())
            {
                error.Append("Người nhận hàng là bắt buộc").Append("</br>");
            }
            if (!txtGoodDecNotificatedParty.Text.HadValue())
            {
                error.Append("Người được thông báo là bắt buộc").Append("</br>");
            }

            return error.ToString();
        }
        #endregion
        #endregion

        #region House Bill Tab

        #region HouseBill
        #region grdHouseBill Event Handlers

        protected void grdHouseBill_SelectedIndexChanged(object sender, EventArgs e)
        {

            foreach (GridViewRow row in grdHouseBill.Rows)
            {
                row.FindControl("grdHouseBillItem").Visible = false;
                ImageButton img = (ImageButton)row.Cells[0].Controls[0];
                img.ImageUrl = "~/_layouts/emanifest/plus.png";
            }



            if (grdHouseBill.Rows.Count > grdHouseBill.SelectedIndex && grdHouseBill.SelectedIndex >= 0)
            {

                odsHouseBillItem.SelectParameters[0].DefaultValue = grdHouseBill.DataKeys[grdHouseBill.SelectedIndex].Value.ToString();// grdHouseBill.SelectedDataKey[0].ToString();
                if (odsHouseBillItem.SelectParameters["userId"] != null)
                    odsHouseBillItem.SelectParameters["userId"].DefaultValue = EmanifestUser.FBAUserId.ToString();
                else
                    odsHouseBillItem.SelectParameters.Add("userId", EmanifestUser.FBAUserId.ToString());

                GridView gv = grdHouseBill.Rows[grdHouseBill.SelectedIndex].FindControl("grdHouseBillItem") as GridView;
                gv.DataSourceID = "odsHouseBillItem";
                gv.DataBind();
                ImageButton img = (ImageButton)grdHouseBill.Rows[grdHouseBill.SelectedIndex].Cells[0].Controls[0];
                img.ImageUrl = "~/_layouts/emanifest/minus.png";

                gv.Visible = true;

                txtHouseBillId.Text = grdHouseBill.DataKeys[grdHouseBill.SelectedIndex].Value.ToString();
            }
        }

        #endregion

        #region Add/Edit House Bill

        protected void grdHouseBill_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            int index = 0;
            string strHouseBillId = string.Empty;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetHouseBill();
                index = int.Parse(e.CommandArgument.ToString());

                BindHouseBillItem(index);

                this.popupHouseBill.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strHouseBillId = this.grdHouseBill.DataKeys[index].Value.ToString();
                Guid houseBillId = new Guid(strHouseBillId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteHouseBill(houseBillId);
                client.Close();
                grdHouseBill.DataBind();
            }

        }
        protected void lnkAddHouseBill_Click(object sender, EventArgs e)
        {
            ResetHouseBill();
            this.popupHouseBill.Show();
        }

        #region Reset/Bind
        private void ResetHouseBill()
        {
            //hfGoodDecralationID.Value = string.Empty;
            txtHouseBillId.Text = string.Empty;
            txtBillNumber.Text = string.Empty;
            txtDateOfBill.Text = string.Empty;
            txtMasterBillNo.Text = string.Empty;
            txtDateOfMasterBill.Text = string.Empty;
            txtDateOfDeparture.Text = string.Empty;
            txtConsigner.Text = (string.Empty);
            txtConsignee.Text = (string.Empty);

            txtHouseBillPortOfLoad.Text = string.Empty;
            txtHouseBillPortOfUnload.Text = string.Empty;
            txtHouseBillPortOfTranship.Text = string.Empty;
            txtHouseBillPortOfDestination.Text = string.Empty;
        }
        private void BindHouseBillItem(int index)
        {
            if (index < 0)
                return;

            txtHouseBillId.Text = this.grdHouseBill.DataKeys[index].Value.ToString();
            GridViewRow row = grdHouseBill.Rows[index];
            int i = 1;
            txtBillNumber.Text = row.Cells[i++].Text;
            txtDateOfBill.Text = row.Cells[i++].Text;
            txtMasterBillNo.Text = row.Cells[i++].Text;
            txtDateOfMasterBill.Text = row.Cells[i++].Text;
            txtDateOfDeparture.Text = row.Cells[i++].Text;
            txtConsigner.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtConsignee.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtHouseBillPortOfTranship.Text = System.Web.HttpUtility.HtmlDecode(GetPortName(row.Cells[i++].Text));
            txtHouseBillPortOfDestination.Text = System.Web.HttpUtility.HtmlDecode(GetPortName(row.Cells[i++].Text));
            txtHouseBillPortOfLoad.Text = System.Web.HttpUtility.HtmlDecode(GetPortName(row.Cells[i++].Text));
            txtHouseBillPortOfUnload.Text = System.Web.HttpUtility.HtmlDecode(GetPortName(row.Cells[i++].Text));
        }
        #endregion
        #endregion

        #region Save/Update

        protected void btnUpdateHouseBill_Click(object sender, EventArgs e)
        {
            string error = ValidationFormHouseBill();
            if (string.IsNullOrEmpty(error))
            {
                Guid houseBillId = Guid.Empty;

                if (!string.IsNullOrEmpty(txtHouseBillId.Text))
                    houseBillId = new Guid(txtHouseBillId.Text);
                else
                    houseBillId = System.Guid.NewGuid();

                HouseBillDto item = new HouseBillDto()
                {
                    HouseBillId = houseBillId,
                    DocumentId = new Guid(hfDocumentID.Value),
                    CreaterId = EmanifestUser.FBAUserId,
                    CreatedDate = DateTime.Now,
                    BillNumber = txtBillNumber.Text.Trim(),
                    DateOfBill = DateTime.Parse(txtDateOfBill.Text, new CultureInfo(Constant.Vi_VN)),
                    MasterBillNo = txtMasterBillNo.Text.Trim(),
                    DateOfMasterBill = DateTime.Parse(txtDateOfMasterBill.Text, new CultureInfo(Constant.Vi_VN)),
                    DepartureDate = DateTime.Parse(txtDateOfDeparture.Text, new CultureInfo(Constant.Vi_VN)),
                    Consignee = txtConsignee.Text.Trim(),
                    Consigner = txtConsigner.Text.Trim(),
                    PortNameOfDestination = txtHouseBillPortOfDestination.Text,
                    PortNameOfLoad = txtHouseBillPortOfLoad.Text,
                    PortNameOfTranship = txtHouseBillPortOfTranship.Text,
                    PortNameOfUnload = txtHouseBillPortOfUnload.Text,

                    NumberOfPackage = 0,

                    PortIdOfDestination = Guid.Empty,
                    PortIdOfLoad = Guid.Empty,
                    PortIdOfTranship = Guid.Empty,
                    PortIdOfUnload = Guid.Empty,
                };
                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.SaveHouseBillRecord(item);
                    client.Close();
                    if (resp.IsSuccess)
                    {
                        grdHouseBill.DataBind();
                        this.popupHouseBill.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SaveHouseBill error: " + resp.ErroeMessage);
                        lblHouseBillError.Text = "SaveHouseBill error: " + resp.ErroeMessage;
                    }
                }
                catch
                {
                    lblHouseBillError.Text = "[" + txtHouseBillId.Text + "], [" + hfDocumentID.Value + "]";
                }
                finally
                {
                    if (client != null) client.Close();
                }
                    #endregion
            }
            else
            {
                lblHouseBillError.Text = error;
                this.popupHouseBill.Show();
            }
        }
        #endregion

        #region validation
        private string ValidationFormHouseBill()
        {
            DateTime dt;
            StringBuilder error = new StringBuilder();
            if (!txtBillNumber.Text.HadValue())
            {
                error.Append("Số vận đơn là bắt buộc").Append("</br>");
            }
            else
                if (!txtBillNumber.Text.IsLessOrEqualLength(34))
                {
                    error.Append("Số vận đơn tối đa 35 kí tự.").Append("</br>");
                }


            if (!DateTime.TryParseExact(txtDateOfBill.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
            {
                error.Append("Ngày vận đơn theo định dạng dd/mm/yyyy").Append("</br>");
            }


            if (!DateTime.TryParseExact(txtDateOfMasterBill.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
            {
                error.Append("Ngày tạo master bill theo định dạng dd/mm/yyyy").Append("</br>");
            }

            if (!txtConsigner.Text.HadValue())
            {
                error.Append("Người gửi hàng là bắt buộc").Append("</br>");
            }
            else
                if (!txtConsigner.Text.IsLessOrEqualLength(255))
                {
                    error.Append("Người gửi hàng tối đa 256 kí tự.").Append("</br>");
                }

            if (!txtConsignee.Text.HadValue())
            {
                error.Append("Người nhận hàng là bắt buộc").Append("</br>");
            }
            else
                if (!txtConsignee.Text.IsLessOrEqualLength(255))
                {
                    error.Append("Người nhận hàng tối đa 256 kí tự.").Append("</br>");
                }

            if (!DateTime.TryParseExact(txtDateOfDeparture.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
            {
                error.Append("Ngày khởi hành theo định dạng dd/mm/yyyy").Append("</br>");
            }

            if (!txtHouseBillPortOfDestination.Text.HadValue())
            {
                error.Append("Cảng giao hàng/cảng đích là bắt buộc").Append("</br>");
            }

            if (!txtHouseBillPortOfTranship.Text.HadValue())
            {
                error.Append("Cảng chuyển tải/quá cảng là bắt buộc").Append("</br>");
            }

            if (!txtHouseBillPortOfLoad.Text.HadValue())
            {
                error.Append("Cảng xếp hàng là bắt buộc").Append("</br>");
            }

            if (!txtHouseBillPortOfUnload.Text.HadValue())
            {
                error.Append("Cảng dỡ hàng là bắt buộc").Append("</br>");
            }


            return error.ToString();
        }
        #endregion
        #endregion

        #region HouseBillItem
        #region grdHouseBillItem Event Handlers
        //This event occurs for any operation on the row of the grid
        protected void grdHouseBillItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "New")
            {
                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    GridView gvTemp = (GridView)sender;
                    gvUniqueID = gvTemp.UniqueID;
                    //Get the values stored in the text boxes
                    Guid houseBillItemId = Guid.Empty;
                    houseBillItemId = Guid.NewGuid();

                    {
                        string txtDescription = ((TextBox)gvTemp.FooterRow.FindControl("txtDescription")).Text;
                        string txtContNumber = ((TextBox)gvTemp.FooterRow.FindControl("txtContNumber")).Text;
                        string txtContSealNumber = ((TextBox)gvTemp.FooterRow.FindControl("txtContSealNumber")).Text;
                        string txtGrossWeight = ((TextBox)gvTemp.FooterRow.FindControl("txtGrossWeight")).Text;
                        string txtDemension = ((TextBox)gvTemp.FooterRow.FindControl("txtDemension")).Text;

                        HouseBillItemDto houseItem = new HouseBillItemDto()
                        {
                            HouseBillItemId = (houseBillItemId),
                            ContNumber = txtContNumber,
                            ContSealNumber = txtContSealNumber,
                            Demension = decimal.Parse(txtDemension),
                            Description = txtDescription,
                            GrossWeight = decimal.Parse(txtGrossWeight),
                            HouseBillId = new Guid(txtHouseBillId.Text)
                        };

                        client = new eManifestService.EmanifestServiceClient();
                        client.SaveHouseBillItemRecord(houseItem);
                        client.Close();

                        gvTemp.DataBind();
                        //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
                        //lblHouseBillLoadStatus.Text = txtDescription + " House bill item added successfully";
                        EmanifestCommon.ShowMessageWithUpdatePanel(this.Page, "House bill item added successfully");
                    }
                }
                catch (Exception ex)
                {
                    //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");\\
                    EmanifestCommon.ShowMessage(this.Page, ex.Message.ToString().Replace("'", ""));
                }
                finally
                {
                    if (client != null) client.Close();
                }
            }           

        }
     
        protected void grdHouseBillItem_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            gvEditIndex = e.NewEditIndex;
            //GridView1.DataBind();


        }

        protected void grdHouseBillItem_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            gvTemp.EditIndex = -1;
            //gvEditIndex = -1;
            //GridView1.DataBind();
        }

        protected void grdHouseBillItem_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("vgHouseBillItemEdit");
            if (!Page.IsValid)
            {
                e.Cancel = true;
                lblHouseBillLoadStatus.Text = "Page is not valid";
            }
            else
            {
                lblHouseBillLoadStatus.Text = string.Empty;
                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    GridView gvTemp = (GridView)sender;
                    gvUniqueID = gvTemp.UniqueID;
                    int index = e.RowIndex;
                    //Get the values stored in the text boxes
                    string houseBillItemStr = gvTemp.DataKeys[index].Value.ToString();  //houseBillItem ID is stored as DataKeyNames
                    Guid houseBillItemId = Guid.Empty;
                    if (!string.IsNullOrEmpty(houseBillItemStr))
                    {
                        houseBillItemId = new Guid(houseBillItemStr);

                        string txtDescription = ((TextBox)gvTemp.Rows[index].FindControl("txtDescription")).Text;
                        string txtContNumber = ((TextBox)gvTemp.Rows[index].FindControl("txtContNumber")).Text;
                        string txtContSealNumber = ((TextBox)gvTemp.Rows[index].FindControl("txtContSealNumber")).Text;
                        string txtGrossWeight = ((TextBox)gvTemp.Rows[index].FindControl("txtGrossWeight")).Text;
                        string txtDemension = ((TextBox)gvTemp.Rows[index].FindControl("txtDemension")).Text;

                        HouseBillItemDto item = new HouseBillItemDto()
                        {
                            HouseBillItemId = (houseBillItemId),
                            ContNumber = txtContNumber,
                            ContSealNumber = txtContSealNumber,
                            Demension = decimal.Parse(txtDemension),
                            Description = txtDescription,
                            GrossWeight = decimal.Parse(txtGrossWeight),
                            HouseBillId = new Guid(gvTemp.DataKeys[index].Values[1].ToString()),
                        };

                        client = new eManifestService.EmanifestServiceClient();
                        ResponseDto resp =client.SaveHouseBillItemRecord(item);
                        client.Close();

                        gvTemp.DataBind();

                        EmanifestCommon.ShowMessageWithUpdatePanel(this.Page, "House bill item updated successfully");

                    }

                }
                catch { }
                finally
                {
                    if (client != null) client.Close();
                }
            }
        }

        protected void grdHouseBillItem_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            //Check if there is any exception while deleting
            if (e.Exception != null)
            {
                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
                //EmanifestCommon.ShowMessageWithUpdatePanel(this.Page, e.Exception.Message.ToString().Replace("'", ""));
                e.ExceptionHandled = true;
            }
        }

        protected void grdHouseBillItem_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            eManifestService.EmanifestServiceClient client = null;
            int index = e.RowIndex;
            try
            {
                string houseBillItemStr = gvTemp.DataKeys[index].Value.ToString();  //houseBillItem ID is stored as DataKeyNames
                Guid houseBillItemId = Guid.Empty;
                if (!string.IsNullOrEmpty(houseBillItemStr))
                {
                    houseBillItemId = new Guid(houseBillItemStr);
                    client = new eManifestService.EmanifestServiceClient();
                    client.DeleteHouseBillItem(houseBillItemId);
                    client.Close();

                    EmanifestCommon.ShowMessageWithUpdatePanel(this.Page, "House Bill item deleted successfully"); 
                    gvTemp.DataBind();

                }

                //GridView1.DataBind();
            }
            catch { }
            finally
            {
                if (client != null) client.Close();
            }
        }

        protected void grdHouseBillItem_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            //Check if there is any exception while deleting
            if (e.Exception != null)
            {
                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
                //EmanifestCommon.ShowMessageWithUpdatePanel(this.Page, e.Exception.Message.ToString().Replace("'", ""));
                e.ExceptionHandled = true;
            }
        }
        #endregion

        #endregion

        //#region Add/Edit Crew Effect

        //protected void grdHouseBillItem_RowCommand(object sender, GridViewCommandEventArgs e)
        //{
        //    //List<CrewDto> items = new List<CrewDto>();

        //    //if (ViewState["crewsitems"] != null)
        //    //{
        //    //    items = (List<CrewDto>)ViewState["crewsitems"];
        //    //}
        //    int index = 0;
        //    string strHouseBillItemId = string.Empty;

        //    if (e.CommandName == "imgedit")
        //    {
        //        //edit/
        //        ResetHouseBillItem();
        //        index = int.Parse(e.CommandArgument.ToString());

        //        BindHouseBillItemItem(index);


        //    }
        //    else if (e.CommandName == "imgremove")
        //    {
        //        index = int.Parse(e.CommandArgument.ToString());
        //        strHouseBillItemId = this.grdCrews.DataKeys[index].Value.ToString();
        //        Guid HouseBillItemId = new Guid(strHouseBillItemId);
        //        eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
        //        client.DeleteCrewById(HouseBillItemId);
        //        client.Close();
        //        grdHouseBillItem.dat ();
        //    }

        //}
        //protected void lnkAddHouseBillItem_Click(object sender, EventArgs e)
        //{
        //    ResetHouseBillItem();
        //    //this.popupHouseBillItem.Show();
        //}

        //#region Reset/Bind
        //private void ResetHouseBillItem()
        //{
        //    //lblHouseBillItemError.Text = string.Empty;
        //    //txtHouseBillItemId.Text = string.Empty;
        //    //txtHoTen.Text = string.Empty;
        //    //txtChucDanh2.Text = string.Empty;
        //    //txtHanhLy.Text = string.Empty;
        //}
        //private void BindHouseBillItemItem(int index)
        //{
        //    if (index < 0)
        //        return;
        //    //GridViewRow row = grdHouseBillItem.Rows[index];
        //    txtHouseBillItemId.Text = this.grdHouseBillItem.DataKeys[index].Value.ToString();

        //    //int i = 0;
        //    //txtHoTen.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //    //txtChucDanh2.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //    //txtHanhLy.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //}
        //#endregion
        //#endregion
        //#region Save/Update

        //protected void btnUpdateHouseBillItem_Click(object sender, EventArgs e)
        //{
        //}
        //#endregion

        #region validation

        #endregion
        #endregion


        #region GeneralDecralation Tab
        #region Add/Edit Crew Effect



        #region Reset/Bind
        private void ResetGeneralDecralation()
        {

        }
        private void BindGeneralDecralationItem(GeneralDeclarationDto general)
        {
            List<PortDto> lstPort = Cache[CacheKey.CacheNameOfListPortInVN] as List<PortDto>;
            if (lstPort == null)
            {
                var client = new EmanifestServiceClient();
                lstPort = client.GetListPortInVN();
                client.Close();
            }
            ddlDeparturePort.DataSource = lstPort;
            ddlDeparturePort.DataBind();

            if (general != null)
            {
                txtGDPosition.Text = lblPosition0.Text = general.PositionInPort;
                lblDeparturePort0.Text = general.DeparturePort.Name;

                ddlDeparturePort.SelectedValue = general.DeparturePortId.ToString();

                txtPreviousPort.Text = lblPreviousPorts0.Text = general.PreviousPorts;
                txtSubsequentPorts.Text = lblSubsequentPorts0.Text = general.SubsequentPorts;
                txtParticularsOfVoyage.Text = lblParticularsOfVoyage0.Text = general.ParticularsOfVoyage;
                txtContactDetails.Text = lblContactDetails0.Text = general.ContactDetails;
                txtDesProduct.Text = lblDesProduct0.Text = general.DescriptionOfCargo;
                txtNumberCrews.Text = lblNumberCrews0.Text = general.NumberOfCrews.ToString();
                txtNumberCustomer.Text = lblNumberCustomer0.Text = general.NumberOfPassengers.ToString();
                txtNode.Text = lblNode0.Text = general.Remarks;
                txtRequire.Text = lblRequire0.Text = general.Requirements;
                txtGeneralDeclarationId.Text = general.GeneralDeclarationId.ToString();
            }
            else
                ddlDeparturePort.SelectedIndex = 0;
        }
        #endregion
        #endregion

        #region Save/Update

        protected void btnUpdateGeneralDecralation_Click(object sender, EventArgs e)
        {
            string error = ValidationFormGeneralDecralation();
            if (string.IsNullOrEmpty(error))
            {
                GeneralDeclarationDto item = new GeneralDeclarationDto();

                if (!string.IsNullOrEmpty(txtGeneralDeclarationId.Text))
                    item.GeneralDeclarationId = new Guid(txtGeneralDeclarationId.Text);
                else
                    item.GeneralDeclarationId = System.Guid.NewGuid();

                item.ContactDetails = txtContactDetails.Text;
                item.CreaterId = EmanifestUser.FBAUserId;
                item.DescriptionOfCargo = txtDesProduct.Text;
                item.DocumentId = new Guid(hfDocumentID.Value);
                item.DeparturePortId = new Guid(ddlDeparturePort.SelectedValue);
                item.ModifiedDate = DateTime.Now.Date;
                item.NumberOfCrews = int.Parse(txtNumberCrews.Text);
                item.NumberOfPassengers = int.Parse(txtNumberCustomer.Text);
                item.ParticularsOfVoyage = txtParticularsOfVoyage.Text;
                item.PositionInPort = txtGDPosition.Text;
                item.PreviousPorts = txtPreviousPort.Text;
                item.Requirements = txtRequire.Text;
                item.Remarks = txtNode.Text;
                item.SubsequentPorts = txtSubsequentPorts.Text;

                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.SaveGeneralDeclaration(item);
                    client.Close();
                    if (resp.IsSuccess)
                    {
                        item.DeparturePort = new PortDto()
                        {
                            PortId = item.DeparturePortId,
                            Name = ddlDeparturePort.SelectedItem.Text
                        };
                        BindGeneralDecralationItem(item);
                        this.popupHouseBill.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SaveGeneralDeclaration error: " + resp.ErroeMessage);
                        lblHouseBillError.Text = "SaveGeneralDeclaration error: " + resp.ErroeMessage;
                    }
                }
                catch
                {
                    lblHouseBillError.Text = "[" + txtGeneralDeclarationId.Text + "], [" + hfDocumentID.Value + "]";
                }
                finally
                {
                    if (client != null) client.Close();
                }
                    #endregion
            }
            else
            {
                lblGeneralDecralationError.Text = error;
                popupGeneralDecralation.Show();
            }
        }
        #endregion

        #region validation
        private string ValidationFormGeneralDecralation()
        {
            StringBuilder error = new StringBuilder();
            DateTime dt;

            //if (ddlDeparturePort.Text.HadValue())
            //{
            //    error.Append("Cảng rời/cảng đích là bắt buộc").Append("</br>");
            //}

            if (!txtContactDetails.Text.HadValue())
            {
                error.Append("Tên và địa chỉ liên lạc của đại lý là bắt buộc").Append("</br>");
            }

            if (!txtDesProduct.Text.HadValue())
            {
                error.Append("Mô tả tóm tắt về hàng hóa là bắt buộc").Append("</br>");
            }
            if (!txtNumberCrews.Text.HadValue())
            {
                error.Append("Số thuyền viên là bắt buộc").Append("</br>");
            }
            else if (!txtNumberCrews.Text.IsNumber())
            {
                error.Append("Số thuyền viên là phải số").Append("</br>");
            }
            if (!txtNumberCustomer.Text.HadValue())
            {
                error.Append("Số hành khách là bắt buộc").Append("</br>");
            }
            else if (!txtNumberCustomer.Text.IsNumber())
            {
                error.Append("Số hành khách là phải số").Append("</br>");
            }

            return error.ToString();
        }
        #endregion
        #endregion

        #region Crews tab
        #region Upload

        #endregion

        #region Add/Edit Crews

        protected void grdCrews_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //List<CrewDto> items = new List<CrewDto>();

            //if (ViewState["crewsitems"] != null)
            //{
            //    items = (List<CrewDto>)ViewState["crewsitems"];
            //}
            int index = 0;
            string strCrewId = string.Empty;
            Guid crewId;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetCrew();

                index = int.Parse(e.CommandArgument.ToString());

                ////Binding
                //CrewDto item = client.GetCrewById(crewId);

                List<PassportTypeDto> lstPassType = Cache[CacheKey.CacheNameOfPassportType] as List<PassportTypeDto>;
                List<StateDto> lstState = Cache[CacheKey.CacheNameOfListState] as List<StateDto>;
                if (lstPassType == null || lstState == null)
                {
                    eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                    if (lstPassType == null)
                        lstPassType = client.GetListPassportType();

                    if (lstState == null)
                        lstState = client.GetListState();

                    client.Close();
                }
                BindCrewItem(index);

                ddlLoaiHoChieu.DataSource = lstPassType;
                ddlLoaiHoChieu.DataBind();

                ddlQuocTich.DataSource = lstState;
                ddlQuocTich.DataBind();

                #region cache
                if (Cache[CacheKey.CacheNameOfPassportType] == null)
                    Cache.Insert(CacheKey.CacheNameOfPassportType, lstPassType, null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                if (Cache[CacheKey.CacheNameOfListState] == null)
                    Cache.Insert(CacheKey.CacheNameOfListState, lstState, null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                #endregion

                this.popupCrew.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strCrewId = this.grdCrews.DataKeys[index].Value.ToString();
                crewId = new Guid(strCrewId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteCrewById(crewId);
                client.Close();
                grdCrews.DataBind();
            }

        }
        protected void lnkAddCrew_Click(object sender, EventArgs e)
        {
            ResetCrew();
            List<PassportTypeDto> lstPassType = Cache[CacheKey.CacheNameOfPassportType] as List<PassportTypeDto>;
            List<StateDto> lstState = Cache[CacheKey.CacheNameOfListState] as List<StateDto>;
            if (lstPassType == null || lstState == null)
            {
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                if (lstPassType == null)
                    lstPassType = client.GetListPassportType();

                if (lstState == null)
                    lstState = client.GetListState();

                client.Close();
            }            

            ddlLoaiHoChieu.DataSource = lstPassType;
            ddlLoaiHoChieu.DataBind();

            ddlQuocTich.DataSource = lstState;
            ddlQuocTich.DataBind();

            this.popupCrew.Show();
        }

        protected void btnUpdateCrew_Click(object sender, EventArgs e)
        {
            string error = ValidationFormCrew();
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    CrewDto item = new CrewDto();

                    if (!string.IsNullOrEmpty(txtCrewId.Text))
                        item.CrewId = new Guid(txtCrewId.Text);
                    else
                        item.CrewId = System.Guid.NewGuid();

                    DateTime today = DateTime.Now;
                    //Bingding data
                    item.DocumentId = new Guid(hfDocumentID.Value);
                    item.CreaterId = EmanifestUser.FBAUserId;
                    item.CreatedDate = today;
                    //item.BirthDate = cNgaySinh.SelectedDate;
                    item.BirthDate = string.IsNullOrEmpty(txtNgaySinh.Text)
                                    ? DateTime.MinValue
                                    : DateTime.Parse(txtNgaySinh.Text, new CultureInfo(Constant.Vi_VN));
                    item.FamilyName = txtHo.Text.Trim();
                    item.GivenName = txtTen.Text.Trim();
                    item.BirthPlace = txtNoiSinh.Text;
                    item.PassportNumber = txtSoHoChieu.Text;
                    item.Rank = txtChucDanh.Text;

                    item.PassportType = ddlLoaiHoChieu.SelectedValue;
                    //item.PassportValidDate = cNgayHetHan.SelectedDate;
                    item.PassportValidDate = string.IsNullOrEmpty(txtNgayHetHan.Text)
                                            ? DateTime.MinValue
                                            : DateTime.Parse(txtNgayHetHan.Text, new CultureInfo(Constant.Vi_VN));
                    item.StateId = new Guid(ddlQuocTich.SelectedValue);
                    item.ItemStatus = 1;

                    //Save 
                    EmanifestServiceClient client = new EmanifestServiceClient();
                    ResponseDto resp = client.SaveCrewRecord(item);
                    if (resp.IsSuccess)
                    {
                        grdCrews.DataBind();
                        this.popupCrew.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        lblCrewError.Text = resp.ErroeMessage;
                        EmanifestCommon.ShowMessage(this.Page, "SaveCrew error " + resp.ErroeMessage);
                    }
                }
                catch 
                {
                    EmanifestCommon.ShowMessage(this.Page, "SaveCrew error");
                    lblCrewError.Text = "SaveCrew error";
                }
                    #endregion
            }
            else
            {
                lblCrewError.Text = error;
                this.popupCrew.Show();
            }
        }

        #endregion

        #region Reset/Bind
        private void ResetCrew()
        {
            lblCrewError.Text = string.Empty;
            hfItemId.Value = string.Empty;
            txtCrewId.Text = string.Empty;
            txtHoRO.Value = txtHo.Text = string.Empty;
            txtTen.Text = string.Empty;
            txtNgayHetHan.Text = string.Empty;
            txtNgaySinh.Text = string.Empty;
            txtSoHoChieu.Text = string.Empty;
            txtChucDanhRO.Text = txtChucDanh.Text = string.Empty;
            txtNoiSinh.Text = string.Empty;
        }
        private void BindCrewItem(int index)
        {
            if (index < 0)
                return;

            txtCrewId.Text = this.grdCrews.DataKeys[index].Value.ToString();
            hfItemId.Value = this.grdCrews.DataKeys[index].Value.ToString();
            GridViewRow row = grdCrews.Rows[index];
            int i = 0;
            txtHoRO.Value = txtHo.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtTen.Text = txtTenRO.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtChucDanh.Text = txtChucDanhRO.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtNgaySinh.Text = row.Cells[i++].Text;
            //cNgaySinh.SelectedDate = DateTime.Parse(row.Cells[i++].Text, new CultureInfo(Constant.Vi_VN)).Date;
            txtNoiSinh.Text = txtNoiSinhRO.Text = row.Cells[i++].Text;
            ddlQuocTich.SelectedValue = this.grdCrews.DataKeys[index].Values[1].ToString(); i++;//row.Cells[i++].Text;
            i++;
            ddlLoaiHoChieu.SelectedValue = this.grdCrews.DataKeys[index].Values[2].ToString(); i++;//row.Cells[i++].Text;
            i++;
            txtSoHoChieu.Text = txtSoHoChieuRO.Text = row.Cells[i++].Text;
            //cNgayHetHan.SelectedDate = DateTime.Parse(row.Cells[i].Text, new CultureInfo(Constant.Vi_VN)).Date;
            txtNgayHetHan.Text = row.Cells[i].Text;
            //lblCrewError.Text = row.Cells[i].Text + ", " + DateTime.Parse(row.Cells[i].Text, new CultureInfo(Constant.Vi_VN)).Date.ToString();

        }
        #endregion

        #region Validation
        private string ValidationFormCrew()
        {
            StringBuilder error = new StringBuilder();
            DateTime dt;
            //error.Append("[").Append(txtHo.Text).Append("], [").Append(txtHoRO.Value).Append("], [").Append(Request[txtHoRO.UniqueID]).Append("]</br>");
            //error.Append("[").Append(txtTen.Text).Append("], [").Append(txtTenRO.Text).Append("], [").Append(Request[txtTenRO.UniqueID]).Append("]</br>");
            //error.Append("[").Append(txtChucDanh.Text).Append("], [").Append(txtChucDanhRO.Text).Append("]</br>");
            //error.Append("[").Append(txtCrewId.Text).Append("], [").Append(hfItemId.Value).Append("]</br>");
            //error.Append("[").Append(hfDocumentID.Value).Append("]</br>");

            if (!txtTen.Text.HadValue())
            {
                error.Append("Họ tên là bắt buộc").Append("</br>");
            }
            else
                if (!txtTen.Text.IsLessOrEqualLength(50))
                {
                    error.Append("Họ tên tối đa 50 kí tự.").Append("</br>");
                }

            if (!txtChucDanh.Text.IsLessOrEqualLength(20))
            {
                error.Append("Chức danh tối đa 20 kí tự.").Append(txtChucDanh.Text).Append("</br>");
            }

            if (txtNgaySinh.Text.HadValue())
                if (!DateTime.TryParseExact(txtNgaySinh.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    error.Append("Ngày sinh phải định dạng dd/mm/yyyy.").Append("</br>");
                }

            if (!txtNoiSinh.Text.HadValue())
            {
                error.Append("Nơi sinh là bắt buộc").Append("</br>");
            }
            else
                if (!txtNoiSinh.Text.IsLessOrEqualLength(200))
                {
                    error.Append("Nơi sinh tối đa 200 kí tự.").Append("</br>");
                }

            if (!txtSoHoChieu.Text.HadValue())
            {
                error.Append("Số hộ chiếu là bắt buộc").Append("</br>");
            }
            else
                if (!txtSoHoChieu.Text.IsLessOrEqualLength(200))
                {
                    error.Append("Số hộ chiếu tối đa 20 kí tự.").Append("</br>");
                }

            if (!txtNgayHetHan.Text.HadValue())
            {
                error.Append("Ngày hết hạn hộ chiếu là bắt buộc").Append("</br>");
            }
            else
                if (!DateTime.TryParseExact(txtNgayHetHan.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    error.Append("Ngày hết hạn hộ chiếu phải định dạng dd/mm/yyyy. [").Append(txtNgayHetHan.Text).Append("]</br>");
                }

            return error.ToString();
        }
        #endregion
        #endregion


        #region CrewwEffect Tab
        #region Add/Edit Crew Effect

        protected void grdCrewEffect_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //List<CrewDto> items = new List<CrewDto>();

            //if (ViewState["crewsitems"] != null)
            //{
            //    items = (List<CrewDto>)ViewState["crewsitems"];
            //}
            int index = 0;
            string strCrewEffectId = string.Empty;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetCrewEffect();
                index = int.Parse(e.CommandArgument.ToString());
                strCrewEffectId = this.grdCrewEffect.DataKeys[index].Value.ToString();
                txtCrewEffectId.Text = strCrewEffectId;

                BindCrewEffectItem(index);

                this.popupCrewEffect.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strCrewEffectId = this.grdCrewEffect.DataKeys[index].Value.ToString();
                Guid crewEffectId = new Guid(strCrewEffectId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteCrewEffectDeclarationById(crewEffectId);
                client.Close();
                grdCrewEffect.DataBind();
            }

        }
        protected void lnkAddCrewEffect_Click(object sender, EventArgs e)
        {
            ResetCrewEffect();
            this.popupCrewEffect.Show();
        }
        protected void btnUpdateCrewEffect_Click(object sender, EventArgs e)
        {
            string error = ValidationFormCrewEffect();
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    CrewEffectDeclarationDto item = new CrewEffectDeclarationDto();

                    if (!string.IsNullOrEmpty(txtCrewEffectId.Text))
                        item.CrewEffectDeclarationId = new Guid(txtCrewEffectId.Text);
                    else
                        item.CrewEffectDeclarationId = System.Guid.NewGuid();

                    DateTime today = DateTime.Now;
                    //Bingding data
                    item.DocumentId = new Guid(hfDocumentID.Value);
                    item.CreaterId = EmanifestUser.FBAUserId;
                    item.CreatedDate = today;
                    //Tanps
                    item.FullName = txtHoTen.Text;
                    item.Rank = txtChucDanh2.Text;
                    item.DutyPackage = txtHanhLy.Text;
                    //Save 
                    EmanifestServiceClient client = new EmanifestServiceClient();
                    //ResponseDto resp = new ResponseDto(); resp.IsSuccess = true; // client.SaveCrewEffectDeclaration(item, false);
                    ResponseDto resp = client.SaveCrewEffectDeclarationRecord(item);
                    if (resp.IsSuccess)
                    {
                        grdCrewEffect.DataBind();
                        this.popupCrewEffect.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        lblCrewEffectError.Text = "SaveCrewEffect error";
                        EmanifestCommon.ShowMessage(this.Page, "SaveCrewEffect error");
                    }
                }
                catch (Exception ex)
                {
                    lblCrewEffectError.Text = "[" + txtCrewEffectId.Text + "], [" + hfDocumentID.Value + "]" + ex.Message + ", " + ex.InnerException.Message;
                }
                    #endregion
            }
            else
            {
                lblCrewEffectError.Text = error;
                this.popupCrewEffect.Show();
            }
        }
        #region Reset/Bind
        private void ResetCrewEffect()
        {
            lblCrewEffectError.Text = string.Empty;
            txtCrewEffectId.Text = string.Empty;
            txtHoTen.Text = string.Empty;
            txtChucDanh2.Text = string.Empty;
            txtHanhLy.Text = string.Empty;
        }
        private void BindCrewEffectItem(int index)
        {
            if (index < 0)
                return;
            GridViewRow row = grdCrewEffect.Rows[index];

            txtCrewEffectId.Text = this.grdCrewEffect.DataKeys[index].Value.ToString();
            int i = 0;
            txtHoTen.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtChucDanh2.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtHanhLy.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        }
        #endregion
        #endregion


        #region validation
        private string ValidationFormCrewEffect()
        {
            StringBuilder error = new StringBuilder();


            if (!txtHoTen.Text.HadValue())
            {
                error.Append("Họ tên là bắt buộc").Append("</br>");
            }
            else
                if (!txtHoTen.Text.IsLessOrEqualLength(50))
                {
                    error.Append("Họ tên tối đa 50 kí tự.").Append("</br>");
                }

            if (!txtChucDanh2.Text.IsLessOrEqualLength(20))
            {
                error.Append("Chức danh tối đa 20 kí tự.").Append(txtChucDanh2.Text).Append("</br>");
            }

            return error.ToString();
        }
        #endregion
        #endregion


        #region ShipStore Tab
        #region grdShipStore Event Handlers
        //This event occurs for any operation on the row of the grid
        protected void grdShipStore_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = 0;
            string strShipStoreId = string.Empty;
            Guid shipStoreId;
            if (e.CommandName == "AddShipStore")
            {
                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    GridView gvTemp = (GridView)sender;
                    gvUniqueID = gvTemp.UniqueID;
                    //Get the values stored in the text boxes
                    Guid ShipStoreId = Guid.Empty;
                    ShipStoreId = Guid.NewGuid();

                    {
                        string txtShipStoreName = ((TextBox)gvTemp.FooterRow.FindControl("txtShipStoreName")).Text;
                        string txtShipStoreQuantity = ((TextBox)gvTemp.FooterRow.FindControl("txtShipStoreQuantity")).Text;

                        ShipStoreItemDto item = new ShipStoreItemDto()
                        {
                            ShipStoreDeclarationId = new Guid(txtShipStoreDeclarationId.Text),
                            ShipStoreItemId = ShipStoreId,
                            Name = txtShipStoreName,
                            Quantity = int.Parse(txtShipStoreQuantity)
                        };

                        client = new eManifestService.EmanifestServiceClient();
                        ResponseDto resp = client.SaveShipStoreItemRecord(item);
                        client.Close();

                        gvTemp.DataBind();
                        //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
                        EmanifestCommon.ShowMessage(this.Page, "Ship Store item added successfully");
                    }
                }
                catch (Exception ex)
                {
                    //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");\\
                    EmanifestCommon.ShowMessage(this.Page, ex.Message.ToString().Replace("'", ""));
                }
                finally
                {
                    if (client != null) client.Close();
                }
            }
            else if (e.CommandName == "DeleteShipStore")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strShipStoreId = this.grdShipStore.DataKeys[index].Value.ToString();
                shipStoreId = new Guid(strShipStoreId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteShipStoreItem(shipStoreId);
                client.Close();
                grdShipStore.DataBind();
            }

        }
        protected void grdShipStore_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            //gvEditIndex = e.NewEditIndex;
            //GridView1.DataBind();


        }

        protected void grdShipStore_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            //gvEditIndex = -1;
            //GridView1.DataBind();
        }

        protected void grdShipStore_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            eManifestService.EmanifestServiceClient client = null;
            try
            {
                GridView gvTemp = (GridView)sender;
                gvUniqueID = gvTemp.UniqueID;
                int index = e.RowIndex;
                //Get the values stored in the text boxes
                string ShipStoreStr = gvTemp.DataKeys[index].Value.ToString();  //ShipStore ID is stored as DataKeyNames
                Guid ShipStoreId = Guid.Empty;
                if (!string.IsNullOrEmpty(ShipStoreStr))
                {
                    ShipStoreId = new Guid(ShipStoreStr);

                    string txtShipStoreName = ((TextBox)gvTemp.FooterRow.FindControl("txtShipStoreName")).Text;
                    string txtShipStoreQuantity = ((TextBox)gvTemp.FooterRow.FindControl("txtShipStoreQuantity")).Text;

                    ShipStoreItemDto item = new ShipStoreItemDto()
                    {
                        ShipStoreDeclarationId = new Guid(txtShipStoreDeclarationId.Text),
                        ShipStoreItemId = ShipStoreId,
                        Name = txtShipStoreName,
                        Quantity = int.Parse(txtShipStoreQuantity)
                    };

                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.SaveShipStoreItemRecord(item);
                    client.Close();

                    gvTemp.DataBind();

                    //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
                    EmanifestCommon.ShowMessage(this.Page, "Ship Store item updated successfully");

                    ////Reset Edit Index
                    //gvEditIndex = -1;
                }
                else
                {
                    EmanifestCommon.ShowMessage(this.Page, ShipStoreStr);
                }

            }
            catch { }
            finally
            {
                if (client != null) client.Close();
            }

        }

        protected void grdShipStore_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            //Check if there is any exception while deleting
            if (e.Exception != null)
            {
                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
                EmanifestCommon.ShowMessage(this.Page, e.Exception.Message.ToString().Replace("'", ""));
                e.ExceptionHandled = true;
            }
        }

        protected void grdShipStore_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            eManifestService.EmanifestServiceClient client = null;
            try
            {
                string ShipStoreStr = gvTemp.DataKeys[0].Value.ToString();  //ShipStore ID is stored as DataKeyNames
                Guid ShipStoreId = Guid.Empty;
                if (!string.IsNullOrEmpty(ShipStoreStr))
                {
                    ShipStoreId = new Guid(ShipStoreStr);
                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.DeleteShipStoreDeclaration(ShipStoreId);
                    client.Close();

                    grdHouseBill.DataBind();

                    EmanifestCommon.ShowMessage(this.Page, "Ship Store item deleted successfully");
                }

                //GridView1.DataBind();
            }
            catch { }
            finally
            {
                if (client != null) client.Close();
            }
        }

        protected void grdShipStore_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            //Check if there is any exception while deleting
            if (e.Exception != null)
            {
                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
                EmanifestCommon.ShowMessage(this.Page, e.Exception.Message.ToString().Replace("'", ""));
                e.ExceptionHandled = true;
            }
        }

        #endregion

        #region Add/Edit Ship Store

        protected void lnkEditShipStore_Click(object sender, EventArgs e)
        {
            ResetShipStore();
            BindShipStoreItem();
            this.popupShipStore.Show();
        }

        protected void lnkAddShipStore_Click(object sender, EventArgs e)
        {
            ResetShipStore();
            this.popupShipStore.Show();
        }

        #region Reset/Bind
        private void ResetShipStore()
        {
            lblShipStoreError.Text = string.Empty;
            txtPeriodOfStay.Text = DateTime.Now.ToString(Constant.FormatDate);
            txtPlaceOfStorage.Text = string.Empty;

        }
        private void BindShipStoreItem()
        {
            txtPeriodOfStay.Text = System.Web.HttpUtility.HtmlDecode(lblPeriodOfStay0.Text);
            txtPlaceOfStorage.Text = System.Web.HttpUtility.HtmlDecode(lblPlaceOfStorage0.Text);
        }

        private void BindShipStore()
        {
            EmanifestServiceClient client = new EmanifestServiceClient();
            ShipStoreDeclarationDto dto = client.GetShipStoreDeclarationByDocumentId(new Guid(hfDocumentID.Value), EmanifestUser.FBAUserId);
            if (dto != null)
            {
                lblPeriodOfStay0.Text = dto.PeriodOfStay.ToString(Constant.FormatDate);
                lblPlaceOfStorage0.Text = dto.PlaceOfStorage;
                txtShipStoreDeclarationId.Text = dto.ShipStoreDeclarationId.ToString();
                lnkAddShipStore.Visible = false;
            }
            else
            {
                lnkEditShipStore.Visible = true;
            }
            client.Close();

        }
        #endregion
        #endregion

        #region Save/Update

        protected void btnUpdateShipStore_Click(object sender, EventArgs e)
        {
            string error = ValidationFormShipStore();
            if (string.IsNullOrEmpty(error))
            {
                ShipStoreDeclarationDto item = new ShipStoreDeclarationDto();

                if (!string.IsNullOrEmpty(txtShipStoreDeclarationId.Text))
                    item.ShipStoreDeclarationId = new Guid(txtShipStoreDeclarationId.Text);
                else
                    item.ShipStoreDeclarationId = System.Guid.NewGuid();

                DateTime today = DateTime.Now;
                //Bingding data
                item.DocumentId = new Guid(hfDocumentID.Value);
                item.CreaterId = EmanifestUser.FBAUserId;
                item.CreatedDate = today;
                item.PeriodOfStay = DateTime.Parse(txtPeriodOfStay.Text, new CultureInfo(Constant.Vi_VN));
                item.PlaceOfStorage = txtPlaceOfStorage.Text.Trim();
                try
                {
                    //Save 
                    EmanifestServiceClient client = new EmanifestServiceClient();
                    ResponseDto resp = client.SaveShipStoreDeclarationRecord(item);
                    if (resp.IsSuccess)
                    {
                        lblPlaceOfStorage0.Text = txtPlaceOfStorage.Text.Trim();
                        lblPeriodOfStay0.Text = txtPeriodOfStay.Text;
                        this.popupCrew.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SaveShipStoreDeclaration error");
                    }
                }
                catch
                {
                    lblShipStoreError.Text = "[" + txtShipStoreDeclarationId.Text + "], [" + hfDocumentID.Value + "]";
                }
                    #endregion
            }
            else
            {
                lblShipStoreError.Text = error;
                popupShipStore.Show();
            }
        }
        #endregion

        #region validation
        private string ValidationFormShipStore()
        {
            StringBuilder error = new StringBuilder();
            DateTime dt;

            if (!txtPlaceOfStorage.Text.HadValue())
            {
                error.Append("Nơi để vật tư là bắt buộc").Append("</br>");
            }

            if (!txtPeriodOfStay.Text.HadValue())
            {
                error.Append("Thời gian ở cảng là bắt buộc").Append("</br>");
            }
            else
                if (!DateTime.TryParseExact(txtPeriodOfStay.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    error.Append("Thời gian phải định dạng dd/mm/yyyy.[").Append(txtPeriodOfStay.Text).Append("]</br>");
                }

            return error.ToString();
        }
        #endregion


        #endregion

        #region Passenger tab
        #region Upload


        protected void lnkUploadPassenger_Click(object sender, EventArgs e)
        {
        }
        #endregion
        #region Add/Edit Passenger

        protected void grdPassenger_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //List<PassengerDto> items = new List<PassengerDto>();

            //if (ViewState["Passengeritems"] != null)
            //{
            //    items = (List<PassengerDto>)ViewState["Passengeritems"];
            //}
            int index = 0;
            string strPassengerId = string.Empty;
            Guid PassengerId;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetPassenger();

                index = int.Parse(e.CommandArgument.ToString());

                ////Binding
                //PassengerDto item = client.GetPassengerById(PassengerId);

                List<PassportTypeDto> lstPassType = Cache[CacheKey.CacheNameOfPassportType] as List<PassportTypeDto>;
                List<StateDto> lstState = Cache[CacheKey.CacheNameOfListState] as List<StateDto>;
                if (lstPassType == null || lstState == null)
                {
                    eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                    if (lstPassType == null)
                        lstPassType = client.GetListPassportType();

                    if (lstState == null)
                        lstState = client.GetListState();

                    client.Close();
                }
                BindPassengerItem(index);

                ddlPassengerLoaiHoChieu.DataSource = lstPassType;
                ddlPassengerLoaiHoChieu.DataBind();

                ddlPassengerQuocTich.DataSource = lstState;
                ddlPassengerQuocTich.DataBind();

                #region cache
                if (Cache[CacheKey.CacheNameOfPassportType] == null)
                    Cache.Insert(CacheKey.CacheNameOfPassportType, lstPassType, null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                if (Cache[CacheKey.CacheNameOfListState] == null)
                    Cache.Insert(CacheKey.CacheNameOfListState, lstState, null, DateTime.Now.AddHours(24), TimeSpan.Zero);
                #endregion

                this.popupPassenger.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strPassengerId = this.grdPassenger.DataKeys[index].Value.ToString();
                PassengerId = new Guid(strPassengerId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeletePassengerById(PassengerId);
                client.Close();
                grdPassenger.DataBind();
            }

        }
        protected void lnkAddPassenger_Click(object sender, EventArgs e)
        {
            ResetPassenger();
            List<PassportTypeDto> lstPassType = Cache[CacheKey.CacheNameOfPassportType] as List<PassportTypeDto>;
            List<StateDto> lstState = Cache[CacheKey.CacheNameOfListState] as List<StateDto>;
            if (lstPassType == null || lstState == null)
            {
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                if (lstPassType == null)
                    lstPassType = client.GetListPassportType();

                if (lstState == null)
                    lstState = client.GetListState();

                client.Close();
            }            

            ddlPassengerLoaiHoChieu.DataSource = lstPassType;
            ddlPassengerLoaiHoChieu.DataBind();

            ddlPassengerQuocTich.DataSource = lstState;
            ddlPassengerQuocTich.DataBind();
            this.popupPassenger.Show();
        }

        protected void btnUpdatePassenger_Click(object sender, EventArgs e)
        {
            string error = ValidationFormPassenger();
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    PassengerDto item = new PassengerDto();

                    if (!string.IsNullOrEmpty(txtPassengerId.Text))
                        item.PassengerId = new Guid(txtPassengerId.Text);
                    else
                        item.PassengerId = System.Guid.NewGuid();

                    DateTime today = DateTime.Now;
                    //Bingding data
                    item.DocumentId = new Guid(hfDocumentID.Value);
                    item.CreaterId = EmanifestUser.FBAUserId;
                    item.CreatedDate = today;
                    item.BirthDate = string.IsNullOrEmpty(txtPassengerNgaySinh.Text)
                                    ? DateTime.MinValue
                                    : DateTime.Parse(txtPassengerNgaySinh.Text, new CultureInfo(Constant.Vi_VN));
                    item.FamilyName = txtPassengerHo.Text.Trim();
                    item.GivenName = txtPassengerTen.Text.Trim();
                    item.BirthPlace = txtPassengerNoiSinh.Text;
                    item.PassportNumber = txtPassengerSoHoChieu.Text;
                    item.IsTransit = chkBoxPassengerIsTransit.Checked;
                    item.PassportType = ddlPassengerLoaiHoChieu.SelectedValue;
                    item.PassportValidDate = string.IsNullOrEmpty(txtPassengerNgayHetHan.Text)
                                            ? DateTime.MinValue
                                            : DateTime.Parse(txtPassengerNgayHetHan.Text, new CultureInfo(Constant.Vi_VN));
                    item.PortIdOfDisembarkation = Guid.Empty;
                    item.PortIdOfEmbarkation = Guid.Empty;
                    item.PortNameOfDisembarkation = txtPassengerPortNameOfDisembarkation.Text.Trim();
                    item.PortNameOfEmbarkation = txtPassengerPortNameOfEmbarkation.Text.Trim();
                    item.StateId = new Guid(ddlPassengerQuocTich.SelectedValue);
                    item.ItemStatus = 1;

                    //Save 
                    EmanifestServiceClient client = new EmanifestServiceClient();
                    ResponseDto resp = client.SavePassengerRecord(item);
                    if (resp.IsSuccess)
                    {
                        grdPassenger.DataBind();
                        this.popupPassenger.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SavePassenger error");
                    }
                }
                catch
                {
                    lblPassengerError.Text = "[" + txtPassengerId.Text + "], [" + hfDocumentID.Value + "]";
                }
                    #endregion
            }
            else
            {
                lblPassengerError.Text = error;
                this.popupPassenger.Show();
            }
        }

        #endregion

        #region Reset/Bind
        private void ResetPassenger()
        {
            lblPassengerError.Text = string.Empty;
            hfItemId.Value = string.Empty;
            txtPassengerId.Text = string.Empty;
            txtPassengerHo.Text = string.Empty;
            txtPassengerTen.Text = string.Empty;
            txtPassengerNgayHetHan.Text = string.Empty;
            txtPassengerNgaySinh.Text = string.Empty;
            txtPassengerSoHoChieu.Text = string.Empty;

            txtPassengerNoiSinh.Text = string.Empty;
            txtPassengerPortNameOfEmbarkation.Text = string.Empty;
            txtPassengerPortNameOfDisembarkation.Text = string.Empty;
        }
        private void BindPassengerItem(int index)
        {
            if (index < 0)
                return;

            txtPassengerId.Text = this.grdPassenger.DataKeys[index].Value.ToString();
            hfItemId.Value = this.grdPassenger.DataKeys[index].Value.ToString();
            GridViewRow row = grdPassenger.Rows[index];
            int i = 0;
            txtPassengerHo.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text.Trim());
            txtPassengerTen.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text.Trim());
            txtPassengerNgaySinh.Text = row.Cells[i++].Text;
            txtPassengerNoiSinh.Text = row.Cells[i++].Text;
            ddlPassengerQuocTich.SelectedValue = this.grdPassenger.DataKeys[index].Values[1].ToString(); i++;//row.Cells[i++].Text;
            i++;
            ddlPassengerLoaiHoChieu.SelectedValue = this.grdPassenger.DataKeys[index].Values[2].ToString(); i++;//row.Cells[i++].Text;
            i++;
            txtPassengerSoHoChieu.Text = row.Cells[i++].Text.Trim();
            txtPassengerNgayHetHan.Text = row.Cells[i++].Text.Trim();
            txtPassengerPortNameOfEmbarkation.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text.Trim());
            txtPassengerPortNameOfDisembarkation.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text.Trim());
            CheckBox chkBox = row.FindControl("chkBoxIsTransit") as CheckBox;
            if (chkBox != null && chkBox.Checked)
                chkBoxPassengerIsTransit.Checked = true;
            else
                chkBoxPassengerIsTransit.Checked = false;
            //lblPassengerError.Text = row.Cells[10].Text;

        }
        #endregion

        #region Validation
        private string ValidationFormPassenger()
        {
            StringBuilder error = new StringBuilder();
            DateTime dt;
            //error.Append("[").Append(txtPassengerHo.Text).Append("], [").Append(txtPassengerHoRO.Value).Append("], [").Append(Request[txtPassengerHoRO.UniqueID]).Append("]</br>");
            //error.Append("[").Append(txtPassengerTen.Text).Append("], [").Append(txtPassengerTenRO.Text).Append("], [").Append(Request[txtPassengerTenRO.UniqueID]).Append("]</br>");
            //error.Append("[").Append(txtPassengerChucDanh.Text).Append("], [").Append(txtPassengerChucDanhRO.Text).Append("]</br>");
            //error.Append("[").Append(txtPassengerPassengerId.Text).Append("], [").Append(hfItemId.Value).Append("]</br>");
            //error.Append("[").Append(hfDocumentID.Value).Append("]</br>");

            if (!txtPassengerTen.Text.HadValue())
            {
                error.Append("Họ tên là bắt buộc").Append("</br>");
            }
            else
                if (!txtPassengerTen.Text.IsLessOrEqualLength(50))
                {
                    error.Append("Họ tên tối đa 50 kí tự.").Append("</br>");
                }


            if (txtPassengerNgaySinh.Text.HadValue())
                if (!DateTime.TryParseExact(txtPassengerNgaySinh.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    error.Append("Ngày sinh phải định dạng dd/mm/yyyy.").Append("</br>");
                }

            if (!txtPassengerNoiSinh.Text.HadValue())
            {
                error.Append("Nơi sinh là bắt buộc").Append("</br>");
            }
            else
                if (!txtPassengerNoiSinh.Text.IsLessOrEqualLength(200))
                {
                    error.Append("Nơi sinh tối đa 200 kí tự.").Append("</br>");
                }

            if (!txtPassengerSoHoChieu.Text.HadValue())
            {
                error.Append("Số hộ chiếu là bắt buộc").Append("</br>");
            }
            else
                if (!txtPassengerSoHoChieu.Text.IsLessOrEqualLength(200))
                {
                    error.Append("Số hộ chiếu tối đa 20 kí tự.").Append("</br>");
                }

            if (!txtPassengerNgayHetHan.Text.HadValue())
            {
                error.Append("Ngày hết hạn hộ chiếu là bắt buộc").Append("</br>");
            }
            else
                if (!DateTime.TryParseExact(txtPassengerNgayHetHan.Text, (Constant.FormatDate), System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                {
                    error.Append("Ngày hết hạn hộ chiếu phải định dạng dd/mm/yyyy. [").Append(txtPassengerNgayHetHan.Text).Append("]</br>");
                }

            if (!txtPassengerPortNameOfEmbarkation.Text.HadValue())
            {
                error.Append("Cảng lên tàu là bắt buộc").Append("</br>");
            }


            if (!txtPassengerPortNameOfDisembarkation.Text.HadValue())
            {
                error.Append("Cảng rời tàu là bắt buộc").Append("</br>");
            }
            return error.ToString();
        }
        #endregion
        #endregion

        #region Dangerous Good Tab

        #region DangerousGood
        #region grdDangerousGood Event Handlers

        protected void grdDangerousGood_SelectedIndexChanged(object sender, EventArgs e)
        {

            foreach (GridViewRow row in grdDangerousGood.Rows)
            {
                row.FindControl("grdDangerousGoodItem").Visible = false;
                ImageButton img = (ImageButton)row.Cells[0].Controls[0];
                img.ImageUrl = "~/_layouts/emanifest/plus.png";
            }

            if (grdDangerousGood.Rows.Count > grdDangerousGood.SelectedIndex && grdDangerousGood.SelectedIndex >= 0)
            {

                odsDangerousGoodItem.SelectParameters[0].DefaultValue = grdDangerousGood.DataKeys[grdDangerousGood.SelectedIndex].Value.ToString();// grdDangerousGood.SelectedDataKey[0].ToString();
                if (odsDangerousGoodItem.SelectParameters["userId"] != null)
                    odsDangerousGoodItem.SelectParameters["userId"].DefaultValue = EmanifestUser.FBAUserId.ToString();
                else
                    odsDangerousGoodItem.SelectParameters.Add("userId", EmanifestUser.FBAUserId.ToString());

                GridView gv = grdDangerousGood.Rows[grdDangerousGood.SelectedIndex].FindControl("grdDangerousGoodItem") as GridView;
                gv.DataSourceID = "odsDangerousGoodItem";
                gv.DataBind();
                ImageButton img = (ImageButton)grdDangerousGood.Rows[grdDangerousGood.SelectedIndex].Cells[0].Controls[0];
                img.ImageUrl = "~/_layouts/emanifest/minus.png";

                gv.Visible = true;

                txtDangerousGoodId.Text = grdDangerousGood.DataKeys[grdDangerousGood.SelectedIndex].Value.ToString();
            }

        }
        protected void grdDangerousGood_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow row = e.Row;
            string strSort = string.Empty;
            string custId = string.Empty;
            // Make sure we aren't in header/footer rows
            if (row.DataItem == null)
            {
                return;
            }
            gvUniqueID = txtDangerousGoodItemUniqueID.Text;
            //Find Child GridView control
            GridView gv = (GridView)row.FindControl("grdDangerousGoodItem");            

            if (gv != null && gv.UniqueID == gvUniqueID)
            {
                string dangerousGoodId = grdDangerousGood.DataKeys[grdDangerousGood.SelectedIndex].Value.ToString();
                //lblDangerousGoodLoadStatus0.Text += "grdDangerousGoodItem EditIndex ->" + gv.EditIndex.ToString() + ", PageIndex ->" + gv.PageIndex.ToString();
                //    odsDangerousGoodItem.SelectParameters[3] != null ? odsDangerousGoodItem.SelectParameters[3].ToString() : " null";
                

                odsDangerousGoodItem.SelectParameters[0].DefaultValue = dangerousGoodId;// grdDangerousGood.SelectedDataKey[0].ToString();
                if (odsDangerousGoodItem.SelectParameters["userId"] != null)
                    odsDangerousGoodItem.SelectParameters["userId"].DefaultValue = EmanifestUser.FBAUserId.ToString();
                else
                    odsDangerousGoodItem.SelectParameters.Add("userId", EmanifestUser.FBAUserId.ToString());
                //lblDangerousGoodLoadStatus0.Text += "<br/>odsDangerousGoodItem EditIndex ->"; //+ odsDangerousGoodItem.SelectParameters[2] != null ? odsDangerousGoodItem.SelectParameters[2].ToString() : " null" +
                //for (int i = 0; i < odsDangerousGoodItem.SelectParameters.Count; i++)
                //    if (odsDangerousGoodItem.SelectParameters[i] != null)
                //        lblDangerousGoodLoadStatus0.Text += i.ToString() + "->" + odsDangerousGoodItem.SelectParameters[i].Name + "=" + odsDangerousGoodItem.SelectParameters[i].DefaultValue + "<br/>";
                //    else
                //        lblDangerousGoodLoadStatus0.Text += i.ToString() + "= null<br/>";
                gv.PageIndex = int.Parse(txtDangerousGoodItemPageIndex.Text);
                gv.DataSourceID = "odsDangerousGoodItem";                
                gv.DataBind();
                //lblDangerousGoodLoadStatus0.Text += "gv.DataSourceID  = " + gv.DataSourceID + "[" + gv.PageIndex.ToString() + "]<br/>";
                ImageButton img = (ImageButton)row.Cells[0].Controls[0];
                img.ImageUrl = "~/_layouts/emanifest/minus.png";

                gv.Visible = true;

                //lblDangerousGoodLoadStatus0.Text += "grdDangerousGoodItem.DataBind ->" + gvUniqueID + ", " + dangerousGoodId;
                txtDangerousGoodId.Text = dangerousGoodId;
            }
        }
        #endregion

        #region Add/Edit House Bill

        protected void grdDangerousGood_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            int index = 0;
            string strDangerousGoodId = string.Empty;

            if (e.CommandName == "imgedit")
            {
                //edit/
                ResetDangerousGood();
                index = int.Parse(e.CommandArgument.ToString());

                BindDangerousGood(index);

                this.popupDangerousGood.Show();
            }
            else if (e.CommandName == "imgremove")
            {
                index = int.Parse(e.CommandArgument.ToString());
                strDangerousGoodId = this.grdDangerousGood.DataKeys[index].Value.ToString();
                Guid dangerousGoodId = new Guid(strDangerousGoodId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteDangerousGood(dangerousGoodId);
                client.Close();
                grdDangerousGood.DataBind();
            }

        }
        protected void lnkAddDangerousGood_Click(object sender, EventArgs e)
        {
            ResetDangerousGood();
            this.popupDangerousGood.Show();
        }

        #region Reset/Bind
        private void ResetDangerousGood()
        {
            //hfGoodDecralationID.Value = string.Empty;
            txtDangerousGoodId.Text = string.Empty;
            txtDangerousContNumber.Text = string.Empty;
            txtDangerousContSealNumber.Text = string.Empty;
            txtDangerousGoodPortOfLoad.Text = string.Empty;
            txtDangerousGoodPortOfUnload.Text = string.Empty;
        }
        private void BindDangerousGood(int index)
        {
            if (index < 0)
                return;

            txtDangerousGoodId.Text = this.grdDangerousGood.DataKeys[index].Value.ToString();
            GridViewRow row = grdDangerousGood.Rows[index];
            int i = 1;
            txtDangerousContNumber.Text = row.Cells[i++].Text;
            txtDangerousContSealNumber.Text =  row.Cells[i++].Text;
            txtDangerousGoodPortOfLoad.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
            txtDangerousGoodPortOfUnload.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        }
        #endregion
        #endregion

        #region Save/Update

        protected void btnUpdateDangerousGood_Click(object sender, EventArgs e)
        {
            string error = ValidationFormDangerousGood();
            if (string.IsNullOrEmpty(error))
            {
                Guid DangerousGoodId = Guid.Empty;

                if (!string.IsNullOrEmpty(txtDangerousGoodId.Text))
                    DangerousGoodId = new Guid(txtDangerousGoodId.Text);
                else
                    DangerousGoodId = System.Guid.NewGuid();

                DangerousGoodDto item = new DangerousGoodDto()
                {
                    DangerousGoodId = DangerousGoodId,
                    DocumentId = new Guid(hfDocumentID.Value),
                    CreaterId = EmanifestUser.FBAUserId,
                    CreatedDate = DateTime.Now,
                    ContNumber = txtDangerousContNumber.Text,
                    ContSealNumber = txtDangerousContSealNumber.Text,
                    PortNameOfLoad = txtDangerousGoodPortOfLoad.Text,
                    PortNameOfUnload = txtDangerousGoodPortOfUnload.Text,

                    PortOfLoad = Guid.Empty,
                    PortOfUnload = Guid.Empty,

                };
                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.SaveDangerousGoodRecord(item);
                    client.Close();
                    if (resp.IsSuccess)
                    {
                        grdDangerousGood.DataBind();
                        this.popupDangerousGood.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SaveDangerousGood error: " + resp.ErroeMessage);
                        lblDangerousGoodError.Text = "SaveDangerousGood error: " + resp.ErroeMessage;
                    }
                }
                catch (Exception ex)
                {
                    lblDangerousGoodError.Text = "[" + txtDangerousGoodId.Text + "], [" + hfDocumentID.Value + "]" + ex.Message + "," + ex.InnerException.Message;
                }
                finally
                {
                    if (client != null) client.Close();
                }
                    #endregion
            }
            else
            {
                lblDangerousGoodError.Text = error;
                this.popupDangerousGood.Show();
            }
        }
        #endregion

        #region validation
        private string ValidationFormDangerousGood()
        {
            StringBuilder error = new StringBuilder();
            string txtContNumber = txtDangerousContNumber.Text;
            string txtSealNumber = txtDangerousContSealNumber.Text;
            string txtPortOfLoad = txtDangerousGoodPortOfLoad.Text;
            string txtPortOfUnload = txtDangerousGoodPortOfUnload.Text;
            if (!txtContNumber.HadValue())
                error.Append("Số hiệu container là bắt buộc").Append("</br>");
            else
                if (!txtContNumber.IsLessOrEqualLength(35))
                    error.Append("Số hiệu container tối đa 35 kí tự.").Append("</br>");
            if (!txtSealNumber.HadValue())
                error.Append("Số seal container là bắt buộc").Append("</br>");
            else
                if (!txtSealNumber.IsLessOrEqualLength(35))
                    error.Append("Số seal container tối đa 35 kí tự.").Append("</br>");
            if (!txtPortOfLoad.HadValue())
                error.Append("Cảng nhận hàng (Port of loading) là bắt buộc").Append("</br>");
            if (!txtPortOfUnload.HadValue())
                error.Append("Cảng dỡ hàng (Port of unloading) là bắt buộc").Append("</br>");
            return error.ToString();
        }
        #endregion
        #endregion

        #region DangerousGoodItem
        #region grdDangerousGoodItem Event Handlers

        protected void grdDangerousGoodItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index;
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;
            txtDangerousGoodItemUniqueID.Text = gvUniqueID;
            txtDangerousGoodItemEditIndex.Text = gvTemp.EditIndex.ToString();
            txtDangerousGoodItemPageIndex.Text = gvTemp.PageIndex.ToString(); //always -1   
            if (e.CommandName == "AddDangerousGoodItem" || e.CommandName == "AddEmptyDangerousGoodItem")
            {
                ResetDangerousGoodItem();
                //lblDangerousGoodItemError.Text = "gvUniqueID = [" + gvUniqueID + "]";
                popupDangerousGoodItem.Show();
            }
            else if (e.CommandName == "imgedit")
            {
                //edit/
                ResetDangerousGoodItem();
                index = int.Parse(e.CommandArgument.ToString());

                BindDangerousGoodItem(gvTemp.Rows[index]);
                txtDangerousGoodItemId.Text = gvTemp.DataKeys[index].Value.ToString();
                this.popupDangerousGoodItem.Show();
            }
            else if (e.CommandName == "DeleteDangerousGoodItem")
            {
                index = int.Parse(e.CommandArgument.ToString());
                string strItemId = gvTemp.DataKeys[index].Value.ToString();
                Guid itemId = new Guid(strItemId);
                eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
                client.DeleteDangerousGoodItemById(itemId);
                client.Close();
                grdDangerousGood.DataBind();
            }

        }
        #endregion


        #region Reset/Bind
        private void ResetDangerousGoodItem()
        {
            //hfGoodDecralationID.Value = string.Empty;

            txtDangerousGoodItemRefNumber.Text = string.Empty;
            txtDangerousGoodItemNumberContainer.Text = string.Empty;
            txtDangerousGoodItemNumberOfPackage.Text = string.Empty;
            txtDangerousGoodItemProperShipping.Text = string.Empty;
            txtDangerousGoodItemGoodClass.Text = string.Empty;
            txtDangerousGoodItemUNNumber.Text = string.Empty;
            txtDangerousGoodItemPackingGroup.Text = string.Empty;
            txtDangerousGoodItemSubsidiaryRisk.Text = string.Empty;
            txtDangerousGoodItemFlashPoint.Text = string.Empty;
            txtDangerousGoodItemMarinePollutant.Text = string.Empty;
            txtDangerousGoodItemGrossWeight.Text = string.Empty;
            txtDangerousGoodItemStowagePosition.Text = string.Empty;

            lblDangerousGoodItemError.Text = string.Empty;
        }
        private void BindDangerousGoodItem(GridViewRow row)
        {            
            //row.ke
            //txtDangerousGoodItemId.Text = this.grdDangerousGood.DataKeys[index].Value.ToString();
            int i = 0;
            txtDangerousGoodItemRefNumber.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemNumberContainer.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemNumberOfPackage.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemProperShipping.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemGoodClass.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemUNNumber.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemPackingGroup.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemSubsidiaryRisk.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemFlashPoint.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemMarinePollutant.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemGrossWeight.Text = row.Cells[i++].Text.Trim();
            txtDangerousGoodItemStowagePosition.Text = row.Cells[i++].Text.Trim();
            lblDangerousGoodItemError.Text = string.Empty;
        }
        #endregion

        #region comment edit inline
        //This event occurs for any operation on the row of the grid
        //protected void grdDangerousGoodItem_RowCommand(object sender, GridViewCommandEventArgs e)
        //{
        //    if (e.CommandName == "AddDangerousGoodItem")
        //    {
        //        GridView gvTemp = (GridView)sender;
        //        gvUniqueID = gvTemp.UniqueID;
        //        string error = ValidationFormDangerousGoodItem(gvTemp.FooterRow);
        //        if (!string.IsNullOrEmpty(error))
        //        {
        //            EmanifestCommon.ShowMessage(this.Page, error);
        //            Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
        //            return;
        //        }
        //        else
        //        {
        //            eManifestService.EmanifestServiceClient client = null;
        //            try
        //            {
        //                //Get the values stored in the text boxes
        //                {
        //                    DangerousGoodItemDto item = FillDangerousGoodItem(gvTemp.FooterRow);
        //                    item.DangerousGoodId = new Guid(txtDangerousGoodId.Text);
        //                    item.DangerousGoodItemId = Guid.NewGuid();

        //                    //client = new eManifestService.EmanifestServiceClient();
        //                    //client.SaveDangerousGoodItem(houseItem);
        //                    //client.Close();

        //                    gvTemp.DataBind();
        //                    //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
        //                    EmanifestCommon.ShowMessage(this.Page, "House bill item added successfully");
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");\\
        //                EmanifestCommon.ShowMessage(this.Page, ex.Message.ToString().Replace("'", ""));
        //            }
        //            finally
        //            {
        //                if (client != null) client.Close();
        //            }
        //        }
        //    }

        //}
        //protected void grdDangerousGoodItem_RowEditing(object sender, GridViewEditEventArgs e)
        //{
        //    GridView gvTemp = (GridView)sender;
        //    gvUniqueID = gvTemp.UniqueID;
        //    //gvEditIndex = e.NewEditIndex;
        //    //GridView1.DataBind();


        //}

        //protected void grdDangerousGoodItem_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
        //{
        //    GridView gvTemp = (GridView)sender;
        //    gvUniqueID = gvTemp.UniqueID;
        //    //gvEditIndex = -1;
        //    //GridView1.DataBind();
        //}

        //protected void grdDangerousGoodItem_RowUpdating(object sender, GridViewUpdateEventArgs e)
        //{
        //    int index = e.RowIndex;

        //    GridView gvTemp = (GridView)sender;
        //    gvUniqueID = gvTemp.UniqueID;
        //    GridViewRow row = gvTemp.Rows[index];
        //    string error = ValidationFormDangerousGoodItem(row);
        //    if (!string.IsNullOrEmpty(error))
        //    {
        //        e.Cancel = true;
        //        EmanifestCommon.ShowMessage(this.Page, error);
        //        Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
        //    }
        //    else
        //    {
        //        eManifestService.EmanifestServiceClient client = null;
        //        try
        //        {
        //            //Get the values stored in the text boxes
        //            string dangerousGoodItemStr = gvTemp.DataKeys[index].Value.ToString();  //DangerousGoodItem ID is stored as DataKeyNames
        //            Guid dangerousGoodItemId = Guid.Empty;
        //            if (!string.IsNullOrEmpty(dangerousGoodItemStr))
        //            {
        //                dangerousGoodItemId = new Guid(dangerousGoodItemStr);
        //                DangerousGoodItemDto item = FillDangerousGoodItem(row);
        //                item.DangerousGoodItemId = (dangerousGoodItemId);
        //                item.DangerousGoodId = new Guid(gvTemp.DataKeys[index].Values[1].ToString());

        //                //client = new eManifestService.EmanifestServiceClient();
        //                //client.SaveDangerousGoodItem(houseItem);
        //                //client.Close();

        //                gvTemp.DataBind();

        //                //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");
        //                EmanifestCommon.ShowMessage(this.Page, "House bill item updated successfully");

        //                ////Reset Edit Index
        //                //gvEditIndex = -1;
        //            }
        //            else
        //            {
        //                EmanifestCommon.ShowMessage(this.Page, dangerousGoodItemStr);
        //            }

        //        }
        //        catch { }
        //        finally
        //        {
        //            if (client != null) client.Close();
        //        }
        //    }
        //}

        //protected void grdDangerousGoodItem_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        //{
        //    //Check if there is any exception while deleting
        //    if (e.Exception != null)
        //    {
        //        //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
        //        EmanifestCommon.ShowMessage(this.Page, e.Exception.Message.ToString().Replace("'", ""));
        //        e.ExceptionHandled = true;
        //    }
        //}

        //protected void grdDangerousGoodItem_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
        //    GridView gvTemp = (GridView)sender;
        //    gvUniqueID = gvTemp.UniqueID;
        //    eManifestService.EmanifestServiceClient client = null;
        //    try
        //    {
        //        string dangerousGoodItemStr = gvTemp.DataKeys[0].Value.ToString();  //DangerousGoodItem ID is stored as DataKeyNames
        //        Guid dangerousGoodItemId = Guid.Empty;
        //        if (!string.IsNullOrEmpty(dangerousGoodItemStr))
        //        {
        //            dangerousGoodItemId = new Guid(dangerousGoodItemStr);
        //            //client = new eManifestService.EmanifestServiceClient();
        //            //client.DeleteDangerousGoodItem(DangerousGoodItemId);
        //            //client.Close();

        //            grdDangerousGood.DataBind();

        //            EmanifestCommon.ShowMessage(this.Page, "Dangerous Good item deleted successfully");
        //        }

        //        //GridView1.DataBind();
        //    }
        //    catch { }
        //    finally
        //    {
        //        if (client != null) client.Close();
        //    }
        //}

        //protected void grdDangerousGoodItem_RowDeleted(object sender, GridViewDeletedEventArgs e)
        //{
        //    //Check if there is any exception while deleting
        //    if (e.Exception != null)
        //    {
        //        //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
        //        EmanifestCommon.ShowMessage(this.Page, e.Exception.Message.ToString().Replace("'", ""));
        //        e.ExceptionHandled = true;
        //    }
        //}
        #endregion
        #endregion

        #region Save/Update
        protected void btnUpdateDangerousGoodItem_Click(object sender, EventArgs e)
        {
            string error = ValidationFormDangerousGoodItem();
            if (string.IsNullOrEmpty(error))
            {
                DangerousGoodItemDto item = FillDangerousGoodItem();
                if (string.IsNullOrEmpty(txtDangerousGoodItemId.Text))
                    item.DangerousGoodItemId = Guid.NewGuid();
                else
                    item.DangerousGoodItemId = new Guid(txtDangerousGoodItemId.Text);

                eManifestService.EmanifestServiceClient client = null;
                try
                {
                    client = new eManifestService.EmanifestServiceClient();
                    ResponseDto resp = client.SaveDangerousGoodItemRecord(item);
                    client.Close();
                    if (resp.IsSuccess)
                    {
                        grdDangerousGood.DataBind();
                        popupDangerousGoodItem.Hide();
                    }
                    else
                    #region Save error handle
                    {
                        EmanifestCommon.ShowMessage(this.Page, "SaveDangerousGoodItemRecord error: " + resp.ErroeMessage);
                        lblDangerousGoodError.Text = "SaveDangerousGoodItemRecord error: " + resp.ErroeMessage;
                    }
                }
                catch
                {
                    lblDangerousGoodError.Text = "[" + txtDangerousGoodId.Text + "], [" + hfDocumentID.Value + "]";
                }
                finally
                {
                    if (client != null) client.Close();
                }
                    #endregion
               
            }
            else
            {
                lblDangerousGoodItemError.Text = error;
                popupDangerousGoodItem.Show();
            }
        }
        #endregion
        #region validation
        private string ValidationFormDangerousGoodItem()
        {
            StringBuilder error = new StringBuilder();
            string txtRefNumber = txtDangerousGoodItemRefNumber.Text.Trim();
            string txtNumberContainer = txtDangerousGoodItemNumberContainer.Text.Trim();
            string txtNumberOfPackage = txtDangerousGoodItemNumberOfPackage.Text.Trim();
            string txtGrossWeight = txtDangerousGoodItemGrossWeight.Text.Trim();
            string txtProperShipping = txtDangerousGoodItemProperShipping.Text.Trim();
            string txtGoodClass = txtDangerousGoodItemGoodClass.Text.Trim();
            string txtUNNumber = txtDangerousGoodItemUNNumber.Text.Trim();
            string txtPackingGroup = txtDangerousGoodItemPackingGroup.Text.Trim();
            string txtSubsidiaryRisk = txtDangerousGoodItemSubsidiaryRisk.Text.Trim();
            string txtFlashPoint = txtDangerousGoodItemFlashPoint.Text.Trim();
            string txtMarinePollutant = txtDangerousGoodItemMarinePollutant.Text.Trim();
            string txtStowagePosition = txtDangerousGoodItemStowagePosition.Text.Trim();

            // if (!txtPassengerTen.Text.HadValue())
            //{
            //    error.Append("Họ tên là bắt buộc").Append("</br>");
            //}
            //else
            //    if (!txtPassengerTen.Text.IsLessOrEqualLength(50))
            //    {
            //        error.Append("Họ tên tối đa 50 kí tự.").Append("</br>");
            //    }

            if (!txtRefNumber.HadValue())
                error.Append("Số vận đơn là bắt buộc").Append("</br>");
            else
                if (!txtRefNumber.IsLessOrEqualLength(35))
                    error.Append("Số vận đơn tối đa 35 kí tự. [").Append(txtRefNumber).Append("]</br>");
            if (!txtGrossWeight.IsNumber())
                error.Append("Tổng khối lượng phải là số").Append("</br>");
            if (!txtFlashPoint.IsNumber())
                error.Append("Điểm bốc cháy phải là số").Append("</br>");

            return error.ToString();
        }
        #endregion

        private DangerousGoodItemDto FillDangerousGoodItem(/*GridViewRow row*/)
        {
            //string txtRefNumber = ((TextBox)row.FindControl("txtRefNumber")).Text;
            //string txtNumberContainer = ((TextBox)row.FindControl("txtNumberContainer")).Text;
            //string txtNumberOfPackage = ((TextBox)row.FindControl("txtNumberOfPackage")).Text;
            //string txtGrossWeight = ((TextBox)row.FindControl("txtGrossWeight")).Text;
            //string txtProperShipping = ((TextBox)row.FindControl("txtProperShipping")).Text;
            //string txtGoodClass = ((TextBox)row.FindControl("txtGoodClass")).Text;
            //string txtUNNumber = ((TextBox)row.FindControl("txtUNNumber")).Text;
            //string txtPackingGroup = ((TextBox)row.FindControl("txtPackingGroup")).Text;
            //string txtSubsidiaryRisk = ((TextBox)row.FindControl("txtSubsidiaryRisk")).Text;
            //string txtFlashPoint = ((TextBox)row.FindControl("txtFlashPoint")).Text;
            //string txtMarinePollutant = ((TextBox)row.FindControl("txtMarinePollutant")).Text;
            //string txtStowagePosition = ((TextBox)row.FindControl("txtStowagePosition")).Text;
            string txtRefNumber = txtDangerousGoodItemRefNumber.Text.Trim();
            string txtNumberContainer = txtDangerousGoodItemNumberContainer.Text.Trim();
            string txtNumberOfPackage = txtDangerousGoodItemNumberOfPackage.Text.Trim();
            string txtGrossWeight = txtDangerousGoodItemGrossWeight.Text.Trim();
            string txtProperShipping = txtDangerousGoodItemProperShipping.Text.Trim();
            string txtGoodClass = txtDangerousGoodItemGoodClass.Text.Trim();
            string txtUNNumber = txtDangerousGoodItemUNNumber.Text.Trim();
            string txtPackingGroup = txtDangerousGoodItemPackingGroup.Text.Trim();
            string txtSubsidiaryRisk = txtDangerousGoodItemSubsidiaryRisk.Text.Trim();
            string txtFlashPoint = txtDangerousGoodItemFlashPoint.Text.Trim();
            string txtMarinePollutant = txtDangerousGoodItemMarinePollutant.Text.Trim();
            string txtStowagePosition = txtDangerousGoodItemStowagePosition.Text.Trim();
            
            DangerousGoodItemDto houseItem = new DangerousGoodItemDto()
            {
                DangerousGoodId = new Guid(txtDangerousGoodId.Text),
                GrossWeight = decimal.Parse(txtGrossWeight),
                RefNumber = txtRefNumber,
                NumberContainer = txtNumberContainer,
                NumberOfPackage = txtNumberOfPackage,

                ProperShipping = txtProperShipping,
                GoodClass = txtGoodClass,
                UNNumber = txtUNNumber,
                PackingGroup = txtPackingGroup,
                SubsidiaryRisk = txtSubsidiaryRisk,
                FlashPoint = decimal.Parse(txtFlashPoint),
                MarinePollutant = txtMarinePollutant,
                StowagePosition = txtStowagePosition,
            };

            return houseItem;
        }
        #endregion


        #region Upload File Completed
        protected void UploadFile_Completed(UploadEventArgs e)
        {
            string msg = e.DocumenType.ToString() + "," + Session["DocumenType"].ToString();
            //lblDocument.Text = msg;

            EnumDoucmentType docType = (EnumDoucmentType)e.DocumenType;
            EmanifestServiceClient client = null;
            switch (docType)
            {
                case EnumDoucmentType.Good:
                    client = new EmanifestServiceClient();
                    GoodDeclarationDto goodDec = client.GetGoodDeclarationByDocumentId(new Guid(hfDocumentID.Value), EmanifestUser.FBAUserId);
                    if (goodDec != null)
                    {
                        txtGoodDecNumberOfPackage0.Text = lblGoodDecNumberOfPackage.Text = goodDec.NumberOfPackage.ToString();
                        txtKindOfPackages0.Text = lblKindOfPackages.Text = goodDec.KindOfPackages;
                        txtGoodDecralationId.Text = goodDec.GoodDeclarationId.ToString();
                    }
                    client.Close();
                    grdGoodDecralationItem.DataBind(); break;
                case EnumDoucmentType.HouseBill:
                    grdHouseBill.DataBind(); break;
                case EnumDoucmentType.General:
                    client = new EmanifestServiceClient();
                    DocumentDto doc = client.GetDocumentDetail(new Guid(hfDocumentID.Value), EmanifestUser.FBAUserId);
                    BindingDocumentDetail(doc);
                    client.Close();
                    break;
                case EnumDoucmentType.Crews:
                    grdCrews.DataBind(); break;
                case EnumDoucmentType.CrewEffect:
                    grdCrewEffect.DataBind(); break;
                case EnumDoucmentType.Stores:
                    BindShipStore();
                    grdShipStore.DataBind(); break;
                case EnumDoucmentType.Passenger:
                    grdPassenger.DataBind(); break;
                case EnumDoucmentType.GoodDangerous:
                    grdDangerousGood.DataBind(); break;
            }

            EmanifestCommon.ShowMessage(this.Page, "Cập nhật hồ sơ thành công.");

        }
        #endregion


        #region private util methods
        private string GetPortName(string portName)
        {
            string[] splits = portName.Split(new char[] { '-' });
            if (splits.Length == 2)
                return splits[1].Trim();
            else
                return portName;
        }
        #endregion



        //#region Template Tab
        //#region Add/Edit Crew Effect

        //protected void grdTemplate_RowCommand(object sender, GridViewCommandEventArgs e)
        //{
        //    //List<CrewDto> items = new List<CrewDto>();

        //    //if (ViewState["crewsitems"] != null)
        //    //{
        //    //    items = (List<CrewDto>)ViewState["crewsitems"];
        //    //}
        //    int index = 0;
        //    string strTemplateId = string.Empty;

        //    if (e.CommandName == "imgedit")
        //    {
        //        //edit/
        //        ResetTemplate();
        //        index = int.Parse(e.CommandArgument.ToString());
        //        strTemplateId = this.grdCrews.DataKeys[index].Value.ToString();
        //        txtTemplateId.Text = strTemplateId;

        //        BindTemplateItem(index);

        //        this.popupTemplate.Show();
        //    }
        //    else if (e.CommandName == "imgremove")
        //    {
        //        index = int.Parse(e.CommandArgument.ToString());
        //        strTemplateId = this.grdCrews.DataKeys[index].Value.ToString();
        //        Guid TemplateId = new Guid(strTemplateId);
        //        eManifestService.EmanifestServiceClient client = new eManifestService.EmanifestServiceClient();
        //        client.DeleteCrewById(TemplateId);
        //        client.Close();
        //        grdTemplate.DataBind();
        //    }

        //}
        //protected void lnkAddTemplate_Click(object sender, EventArgs e)
        //{
        //    ResetTemplate();
        //    //this.popupTemplate.Show();
        //}

        //#region Reset/Bind
        //private void ResetTemplate()
        //{
        //    //lblTemplateError.Text = string.Empty;
        //    //txtTemplateId.Text = string.Empty;
        //    //txtHoTen.Text = string.Empty;
        //    //txtChucDanh2.Text = string.Empty;
        //    //txtHanhLy.Text = string.Empty;
        //}
        //private void BindTemplateItem(int index)
        //{
        //    if (index < 0)
        //        return;
        //    //GridViewRow row = grdTemplate.Rows[index];
        //txtCrewId.Text = this.grdTemplate.DataKeys[index].Value.ToString();

        //    //int i = 0;
        //    //txtHoTen.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //    //txtChucDanh2.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //    //txtHanhLy.Text = System.Web.HttpUtility.HtmlDecode(row.Cells[i++].Text);
        //}
        //#endregion
        //#endregion
        //#region Save/Update

        //protected void btnUpdateTemplate_Click(object sender, EventArgs e)
        //{
        //}
        //#endregion

        //#region validation

        //#endregion
        //#endregion
    }
}
